PHP implementation from the top down to print a binary tree method explained

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

Related Article

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.