This time for everyone to bring PHP implementation from the top down to print binary tree code sharing, PHP implementation from the top down to print the binary tree notes, the following is the actual case, together to see.
Problem
Each node of the two-fork tree is printed from top to bottom, and the same-level node prints from left to right.
Solution Ideas
Each layer of the tree is printed from left to right, so it is necessary to save the tree of the nodes, because first-out, so use the queue.
Implementation code
/*class treenode{ var $val; var $left = NULL; var $right = NULL; function construct ($val) { $this->val = $val; }} */function Printfromtoptobottom ($root) { $queueVal = array (); $queueNode = Array (); if ($root = = NULL) return $queueVal; Array_push ($queueNode, $root); while (!empty ($queueNode)) { $node = Array_shift ($queueNode); if ($node->left! = NULL) array_push ($queueNode, $node->left); if ($node->right! = NULL) array_push ($queueNode, $node->right); Array_push ($queueVal, $node->val); } return $queueVal;}
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
TP5 (thinkPHP5) How to manipulate MongoDB database steps
PHP Implementation MongoDB Singleton mode operation steps