Task description:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
递归版solution:
class Solution{
public:
bool isSymmetric(TreeNode *root){
if (root == nullptr) return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode *p, TreeNode *q){
if (p == nullptr && q == nullptr) return true;//当两个子节点都为nullptr时,则相同
if (p == nullptr || q == nullptr) return false;//当其中有一个为空另一个不为空时,则二者肯定不同,则返回false.
//迭代的“检测两棵树的左子树和右子树”
return p->val == q->val && isSymmetric(p->left, q->left) && isSymmetric(p->right, q->right);
}
}