Home > Article > Backend Development > PHP method to determine whether a binary tree is symmetrical
This article explains how PHP determines whether a binary tree is symmetrical.
The example in this article describes the method of determining whether a binary tree is symmetrical in PHP. 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:
/*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); }
This article explains how PHP determines whether a binary tree is symmetrical. For more related knowledge, please pay attention to the PHP Chinese website.
Related recommendations:
PHP method to implement clockwise printing of matrices and spiral matrices
PHP learning: predefined variables Details
Teach you to use PHP development to implement the WeChat refund function
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!