This time I will share with you the code for PHP to print a binary tree from top to bottom. What are the precautions for PHP to print a binary tree from top to bottom? Here are the actual cases, let's take a look.
Question
Print each node of the binary tree from top to bottom, and print nodes at the same level from left to right.Solution
Each layer of trees is printed from left to right, so the left and right subtrees of the node need to be stored, because first in, first out , so usequeue.
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; }
tp5 (thinkPHP5) Detailed explanation of the steps to operate the mongoDB database
The above is the detailed content of PHP realizes printing binary tree from top to bottom code sharing. For more information, please follow other related articles on the PHP Chinese website!