Home >Backend Development >PHP Tutorial >PHP implementation method to determine whether a binary tree is symmetrical
This article mainly introduces the method of PHP to judge whether a binary tree is symmetrical, involving the relevant operating skills of PHP recursive binary tree judgment nodes. Friends in need can refer to the following.
The example of this article tells the PHP method to judge whether a binary tree is symmetrical. Symmetrical approach. Share it with everyone for your reference, the details are as follows:
Question
Please implement a function to determine whether a binary tree is 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); }
Example of how PHP uses one line of code to delete all files in a directory
PHP gets the first non-repeating character in the character stream Explanation of the method
#A brief discussion on the problems often encountered in PHP string reversal interviews
The above is the detailed content of PHP implementation method to determine whether a binary tree is symmetrical. For more information, please follow other related articles on the PHP Chinese website!