#Binary tree breadth-first traversal
#Using a queue implementation
class node {
 public $data=null;
 public $left=null;
 public $right=null;
#@param $btree binary tree root node
function breadth_first_traverse ($btree) {
 $traverse_data=array ();
 $queue=array ();
 array_unshift ($queue, $btree);#Enqueue the root node
 while (! empty ($queue)) {#continuously output nodes,Until the queue is empty
   $cnode=array_pop ($queue);#Team tail element out of the team
   $traverse_data []=$cnode->data;
   #Left node enqueue first,Then the right node enqueues
   if ($cnode-&left;= null) array_unshift ($queue, $cnode-&left;left);
   if ($cnode->right!=null) array_unshift ($queue, $cnode->right);
 return $traverse_data;
#Depth-first traversal,Use a stack implementation
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;left);
return $traverse_data;
$root=new node ();
$node1=new node ();
$node2=new node ();
$node3=new node ();
$node4=new node ();
$node5=new node ();
$node6=new node ();
$traverse=breadth_first_traverse ($root);
print_r ($traverse);
echo "";
$traverse=depth_first_traverse ($root);
print_r ($traverse);
  • Previous JS phone number verification method
  • Next JS dynamic date and time acquisition method