Method of Obtaining Binary Tree Image by PHP

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

In this paper, an example is given to describe the method of obtaining 2-tree image by PHP. Share it for your reference, as follows:

Problem

Operates the given 2-tree to transform it into a mirror image of the source 2-tree.

Solutions

There are two ways to flip a 2-tree, recursive and non-recursive. Non-recursive is to use queues.

Implementation code


<?php
/*class TreeNode{
 var $val;
 var $left = NULL;
 var $right = NULL;
 function __construct($val){
  $this->val = $val;
 }
}*/
function Mirror(&$root)
{
 if($root == NULL)
  return 0;
 $queue = array();
 array_push($queue, $root);
 while(!empty($queue)){
  $node = array_shift($queue);
  $tmp = $node->left;
  $node->left = $node->right;
  $node->right = $tmp;
  if($node->left != NULL)
   array_push($queue, $node->left);
  if($node->right != NULL)
   array_push($queue, $node->right);
 }
}

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: