PHP implements the method of printing a binary tree from top to bottom, and php prints a binary tree from top to bottom.

Source: Internet
Author: User

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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.