PHP的各种遍历

<?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 );
?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值