<?php
#二叉树的非递归遍历
class Node {
public $data;
public $left;
public $right;
}
#前序遍历,和深度遍历一样
function preorder($root) {
$stack = array ();
array_push ( $stack, $root );
while ( ! empty ( $stack ) ) {
$cnode = array_pop ( $stack );
echo $cnode->data . " ";
if ($cnode->right != null)
array_push ( $stack, $cnode->right );
if ($cnode->left != null)
array_push ( $stack, $cnode->left );
}
}
#中序遍历
function inorder($root) {
$stack = array ();
$cnode = $root;
while ( ! empty ( $stack ) || $cnode != null ) {
while ( $cnode != null ) {
array_push ( $stack, $cnode );
$cnode = $cnode->left;
}
$cnode = array_pop ( $stack );
echo $cnode->data . " ";
$cnode = $cnode->right;
}
}
#后序遍历
#使用双栈实现
function postorder($root) {
$pushstack = array ();
$visitstack = array ();
array_push ( $pushstack, $root );
while ( ! empty ( $pushstack ) ) {
$cnode = array_pop ( $pushstack );
array_push ( $visitstack, $cnode );
if ($cnode->left != null)
array_push ( $pushstack, $cnode->left );
if ($cnode->right != null)
array_push ( $pushstack, $cnode->right );
}
while ( ! empty ( $visitstack ) ) {
$cnode = array_pop ( $visitstack );
echo $cnode->data . " ";
}
}
$root = new Node ();
$n1 = new Node ();
$n11 = new Node ();
$n12 = new Node ();
$n2 = new Node ();
$n21 = new Node ();
$n22 = new Node ();
$n111 = new Node ();
$n112 = new Node ();
$root->data = 0;
$n1->data = 1;
$n11->data = 11;
$n111->data = 111;
$n112->data = 112;
$n12->data = 12;
$n2->data = 2;
$n21->data = 21;
$n22->data = 22;
$root->left = $n1;
$root->right = $n2;
$n1->left = $n11;
$n1->right = $n12;
$n2->left = $n21;
$n2->right = $n22;
$n11->left = $n111;
$n11->right = $n112;
preorder ( $root );
echo "<br>";
inorder ( $root );
echo "<br>";
postorder ( $root );
?>
PHP的各种遍历
最新推荐文章于 2024-09-16 19:32:17 发布