Explanation of how to obtain binary tree image in PHP

jacklove
Release: 2023-04-02 07:40:01
Original
1525 people have browsed it

This article mainly introduces the method of PHP to obtain the binary tree image, involving the related operation skills of PHP using queue to flip the binary tree. Friends in need can refer to the following

The example of this article tells the method of PHP to obtain the binary tree image. method. Share it with everyone for your reference, the details are as follows:

Question

Operate the given binary tree and transform it into a mirror image of the source binary tree.

Solution idea

There are two ways to flip the binary tree, recursive and non-recursive. Non-recursive is to use a queue.

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

You may be interested Article:

Explanation on how PHP obtains the K-th node from the last in a linked list

Explanation on how PHP can print a binary tree from top to bottom

php method of sending custom data through header_php tips

##

The above is the detailed content of Explanation of how to obtain binary tree image 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!