Skip to content

101. 对称二叉树 #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Doragd opened this issue Dec 16, 2023 · 0 comments
Open

101. 对称二叉树 #6

Doragd opened this issue Dec 16, 2023 · 0 comments

Comments

@Doragd
Copy link
Owner

Doragd commented Dec 16, 2023

  • 给你一个二叉树的根节点 root, 检查它是否轴对称。
  • 递归遍历+问题分解+分类讨论
    • 子结构: 两棵小树p和q, 同步遍历两棵树
    • 终止条件:p和q其中一方为空 或者 p 和 q不相等 return false
    • 否则: 递归判定: (左子树,右子树) (右子树,左子树)
class Solution {
public:
    //递归遍历+分类讨论:
    //子结构: 两棵小树p和q, 同步遍历两棵树
    //p和q其中一方为空 或者 p 和 q不相等 return false
    //否则: 递归判定: (左子树,右子树) (右子树,左子树)
    bool dfs(TreeNode *p, TreeNode *q){
        if(!p && !q) return true;
        if(p && q && p->val == q->val) return dfs(p->left, q->right) && dfs(p->right, q->left);
        return false;
    }
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return dfs(root->left, root->right);
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant