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
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!