Home > Backend Development > PHP Tutorial > How to print a binary tree from top to bottom in PHP

How to print a binary tree from top to bottom in PHP

韦小宝
Release: 2023-03-19 15:12:01
Original
1185 people have browsed it

This article mainly introduces the method of printing binary trees from top to bottom in PHP, involving operating techniques related to PHP binary tree traversal. Friends who are interested in PHP can refer to this article

The examples in this article describe PHP implements the method of printing a binary tree from top to bottom. 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;
}
Copy after login

The above is all the content of this article, I hope it can help everyone learn PHP! !

Related recommendations:

PHP uses two stacks to implement the queue function

PHP implements pre-order, in-order and post-order traversal of a binary tree Operation example

PHP calls ffmpeg to take video screenshots and splice script examples to share

The above is the detailed content 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!

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