This article mainly introduces the PHP implementation from the top down to print binary tree, involving PHP two cross-tree traversal related operation skills, the need for friends can refer to the following
The example in this paper describes how PHP implements a binary tree printing from top to bottom. Share to everyone for your reference, as follows:
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;}
Articles you may be interested in:
PHP _php tips for sending custom data methods via the header
PHP uses Ob_start () to clear out the output and selectively output the method to explain
PHP implementation merge Two sorted list of methods explained