PHP 二叉树的深度优先与广度优先遍历
1 <?php 2 #二叉树的广度优先遍历 3 #使用一个队列实现 4 5 class Node { 6 public $data = null; 7 public $left = null; 8 public $right = null; 9 } 10 11 #@param $btree 二叉树根节点 12 function breadth_first_traverse($btree) { 13 $traverse_data = array(); 14 $queue = array(); 15 array_unshift($queue, $btree); #根节点入队 16 17 while (!empty($queue)) { #持续输出节点,直到队列为空 18 $cnode = array_pop($queue); #队尾元素出队 19 $traverse_data[] = $cnode->data; 20 21 #左节点先入队,然后右节点入队 22 if ($cnode->left != null) array_unshift($queue, $cnode->left); 23 if ($cnode->right != null) array_unshift($queue, $cnode->right); 24 } 25 26 return $traverse_data; 27 } 28 29 #深度优先遍历,使用一个栈实现 30 function depth_first_traverse($btree) { 31 $traverse_data = array(); 32 $stack = array(); 33 array_push($stack, $btree); 34 35 while (!empty($stack)) { 36 $cnode = array_pop($stack); 37 $traverse_data[] = $cnode->data; 38 39 if ($cnode->right != null) array_push($stack, $cnode->right); 40 if ($cnode->left != null) array_push($stack, $cnode->left); 41 } 42 43 return $traverse_data; 44 } 45 46 $root = new Node(); 47 $node1 = new Node(); 48 $node2 = new Node(); 49 $node3 = new Node(); 50 $node4 = new Node(); 51 $node5 = new Node(); 52 $node6 = new Node(); 53 54 $root->data = 1; 55 $node1->data = 2; 56 $node2->data = 3; 57 $node3->data = 4; 58 $node4->data = 5; 59 $node5->data = 6; 60 $node6->data = 7; 61 62 $root->left = $node1; 63 $root->right = $node2; 64 $node1->left = $node3; 65 $node1->right = $node4; 66 $node2->left = $node5; 67 $node2->right = $node6; 68 69 $traverse = breadth_first_traverse($root); 70 print_r($traverse); 71 echo "<br>"; 72 $traverse = depth_first_traverse($root); 73 print_r($traverse); 74 ?>
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 ) Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 3 [5] => 6 [6] => 7 )
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。