PHP realizes depth first and breadth first traversal method of two fork tree _php skill

Source: Internet
Author: User
Tags php programming

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.