Home  >  Article  >  Backend Development  >  An explanation of how to print a binary tree from top to bottom in PHP

An explanation of how to print a binary tree from top to bottom in PHP

jacklove
jackloveOriginal
2018-06-30 17:46:251430browse

This article mainly introduces the method of printing binary trees from top to bottom in PHP, involving the operation skills related to PHP binary tree traversal. Friends who need it can refer to it

The example of this article tells about the implementation of PHP from top to bottom Method to print binary tree. Share it with everyone for your reference, the details are as follows:

Question

Print each node of the binary tree from top to bottom, nodes at the same level Print 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 use 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;
}

You may be interested Article:

php method of sending custom data through header_php tips

php method to use ob_start() to clear output and selective output Explain

How to merge two sorted linked lists using PHP

##

The above is the detailed content of An explanation of how to print a binary tree from top to bottom in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn