Home  >  Article  >  Backend Development  >  PHP method to determine whether a binary tree is symmetrical

PHP method to determine whether a binary tree is symmetrical

韦小宝
韦小宝Original
2018-01-13 11:56:411184browse

This article mainly introduces the method of judging whether a binary tree is symmetrical in PHP, involving phprecursionrelated operating techniques for judging nodes in a binary tree. Friends who are grateful to PHP can refer to this article

The example of this article describes the method of PHP to determine whether a binary tree is symmetrical. Share it with everyone for your reference, as follows:

Question

Please implement a function to determine a Is this binary tree symmetrical? Note that a binary tree is defined as symmetric if it is the same as the image of the binary tree.

Solution

Recursively judge both sides of the binary 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);
}

The above is all the content of this article. I hope it will be helpful to everyone’s study! !

Related recommendations:

Example comparison of two methods of php method overloading

Simple example of php method calling mode and function calling mode

PHP method tracking

The above is the detailed content of PHP method to determine whether a binary tree is symmetrical. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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