PHP implements the method of printing a binary tree from top to bottom, and php prints a binary tree from top to bottom.
This example describes how PHP can print Binary Trees from top to bottom. We will share this with you for your reference. The details are as follows:
Problem
Each node of the binary tree is printed from top to bottom, and the nodes at the same layer are printed from left to right.
Solution
Each layer of tree is printed from left to right. Therefore, you need to store the Left and Right sub-trees of the node. Because the node is first-in-first-out, the queue is used.
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 ;}