PHP realizes the method of judging whether the binary tree is symmetrical or not

  • 2021-09-04 23:39:42
  • OfStack

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

Problem

Please implement a function to judge whether a 2-tree is symmetric. Note that if a binary tree is the same as the image of this binary tree, it is defined as symmetric.

Problem solution

Recursively judge both sides of a 2-tree.

Implementation code:


<?php
/*class TreeNode{
 var $val;
 var $left = NULL;
 var $right = NULL;
 function __construct($val){
  $this->val = $val;
 }
}*/
function isSymmetrical($pRoot)
{
 if($pRoot==null) return true;
 return compare($pRoot->left,$pRoot->right);
}
function compare($root1,$root2){
 if($root1==null&&$root2==null) return true;
 if($root1==null||$root2==null) return false;
 if($root1->val!=$root2->val) return false;
 return compare($root1->left,$root2->right)&&compare($root1->right,$root2->left);
}

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: