Home  >  Article  >  Backend Development  >  PHP realizes printing binary tree from top to bottom code sharing

PHP realizes printing binary tree from top to bottom code sharing

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 14:47:371259browse

This time I will share with you the code for PHP to print a binary tree from top to bottom. What are the precautions for PHP to print a binary tree from top to bottom? Here are the actual cases, let's take a look.

Question

Print each node of the binary tree from top to bottom, and print nodes at the same level 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;
}
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

tp5 (thinkPHP5) Detailed explanation of the steps to operate the mongoDB database

##php implements the mongoDB singleton mode operation class Detailed explanation of steps

The above is the detailed content of PHP realizes printing binary tree from top to bottom code sharing. 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