Method of Printing Binary Tree from Top to Bottom by PHP

  • 2021-08-31 07:33:41
  • OfStack

In this paper, an example is given to describe the method of printing 2-tree from top to bottom in PHP. Share it for your reference, as follows:

Problem

Each node of the 2-tree is printed from top to bottom, and the nodes of the same layer are printed from left to right.

Solutions

Each tree is printed from left to right, so the left and right subtrees of the node need to be saved, because first in first out, so queue is used.

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;
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: