都利用递归,思路相似;
对称二叉树就是两个相同的二叉树,但是子节点是right = left因为对称;
101. 对称二叉树 - 力扣(LeetCode)
class Solution {
public:
bool isSymmetric(TreeNode* root) {
TreeNode* rt = root->right;
TreeNode* lt = root->left;
return check(lt,rt);
}
bool check(TreeNode* lt,TreeNode* rt){
if(lt == nullptr && rt == nullptr){
return true;
}
else if(lt == nullptr || rt == nullptr){
return false;
}
return lt->val == rt->val && check(lt->right,rt->left) && check(lt->left,rt->right);
}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == nullptr && q == nullptr){
return true;
}
else if(p == nullptr || q == nullptr){
return false;
}
else if(p->val != q->val){
return false;
}
else{
return isSameTree(q->left,p->left) && isSameTree(q->right,p->right);
}
}
};