PHP implementation from top to bottom print binary tree code share

Source: Internet
Author: User
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

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.