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

PHP realizes printing binary tree from top to bottom code sharing

php中世界最好的语言
Release: 2023-03-26 22:26:01
Original
1309 people have browsed it

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;
}
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template