This article illustrates the depth first and breadth first traversal method of PHP two-fork tree. Share to everyone for your reference. as follows:
#二叉树的广度优先遍历 #使用一个队列实现 class Node {public $data = null;
Public $left = null;
public $right = null;
# @param $btree binary root node function breadth_first_traverse ($btree) {$traverse _data = array ();
$queue = Array (); Array_unshift ($queue, $btree); #根节点入队 while (!empty ($queue)) {#持续输出节点 until the queue is empty $cnode = Array_pop ($queue); #队尾元素出队 $traverse _data[] = $cnode->da
Ta
#左节点先入队, then the right node is queued for the IF ($cnode->left!= null) array_unshift ($queue, $cnode->left);
if ($cnode->right!= null) array_unshift ($queue, $cnode->right);
return $traverse _data; #深度优先遍历, use a stack to implement function Depth_first_traverse ($btree) {$traverse _data = array (); $stack = Array (); Array_push ($stack, $
Btree);
while (!empty ($stack)) {$cnode = Array_pop ($stack);
$traverse _data[] = $cnode->data;
if ($cnode->right!= null) Array_push ($stack, $cnode->right);
if ($cnode->left!= null) Array_push ($stack, $cnode->left);
return $traverse _data;
} $root = new Node ();
$node 1 = new Node (); $node 2 = new Node ();
$node 3 = new Node ();
$node 4 = new Node ();
$node 5 = new Node ();
$node 6 = new Node ();
$root->data = 1;
$node 1->data = 2;
$node 2->data = 3;
$node 3->data = 4;
$node 4->data = 5;
$node 5->data = 6;
$node 6->data = 7;
$root->left = $node 1;
$root->right = $node 2;
$node 1->left = $node 3;
$node 1->right = $node 4;
$node 2->left = $node 5;
$node 2->right = $node 6;
$traverse = Breadth_first_traverse ($root);
Print_r ($traverse);
echo "";
$traverse = Depth_first_traverse ($root); Print_r ($traverse);
I hope this article will help you with your PHP programming.