PHP 二叉树非递归遍历

 1 <?php
 2     #二叉树的非递归遍历
 3     class Node {
 4         public $data;
 5         public $left;
 6         public $right;
 7     }
 8 
 9     #前序遍历,和深度遍历一样
10     function preorder($root) {
11         $stack = array();
12         array_push($stack, $root);
13         while (!empty($stack)) {
14             $cnode = array_pop($stack);
15             echo $cnode->data . " ";
16             if ($cnode->right != null) array_push($stack, $cnode->right);
17             if ($cnode->left != null) array_push($stack, $cnode->left);
18         }
19     }
20 
21     #中序遍历
22     function inorder($root) {
23         $stack = array();
24         $cnode = $root;
25         while (!empty($stack) || $cnode != null) {
26             while ($cnode != null) {
27                 array_push($stack, $cnode);
28                 $cnode = $cnode->left;
29             }
30 
31             $cnode = array_pop($stack);
32             echo $cnode->data . " ";
33 
34             $cnode = $cnode->right;
35         }
36     }
37 
38     #后序遍历
39     #使用双栈实现
40     function postorder($root) {
41         $pushstack = array();
42         $visitstack = array();
43         array_push($pushstack, $root);
44 
45         while (!empty($pushstack)) {
46             $cnode = array_pop($pushstack);
47             array_push($visitstack, $cnode);
48             if ($cnode->left != null) array_push($pushstack, $cnode->left);
49             if ($cnode->right != null) array_push($pushstack, $cnode->right);
50         }
51 
52         while (!empty($visitstack)) {
53             $cnode = array_pop($visitstack);
54             echo $cnode->data . " ";
55         }
56     }
57 
58     $root = new Node();
59     $n1 = new Node();
60     $n11 = new Node();
61     $n12 = new Node();
62     $n2 = new Node();
63     $n21 = new Node();
64     $n22 = new Node();
65     $root->data = 0;
66     $n1->data = 1;
67     $n11->data = 11;
68     $n12->data = 12;
69     $n2->data = 2;
70     $n21->data = 21;
71     $n22->data = 22;
72     $root->left = $n1;
73     $root->right = $n2;
74     $n1->left = $n11;
75     $n1->right = $n12;
76     $n2->left = $n21;
77     $n2->right = $n22;
78 
79     preorder($root);
80     echo "<br>";
81     inorder($root);
82     echo "<br>";
83     postorder($root);
84 ?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值