Skip to content

100. 相同的树 #3

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 10, 2023 · 0 comments
Open

100. 相同的树 #3

Doragd opened this issue Dec 10, 2023 · 0 comments

Comments

@Doragd
Copy link
Owner

Doragd commented Dec 10, 2023

  • 100. 相同的树
  • 给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
  • 递归定义法:按照定义法来做
    • 定义: 如果两棵树相等则左子树和左子树相同, 右子树和右子树相同, 且根的值相同
    • 分类讨论终止: pq其中一个为空, 直接返回false; pq均为空, 则返回true
class Solution {
public:
    //递归定义+分类讨论
    //定义: 如果两棵树相等则左子树和左子树相同, 右子树和右子树相同, 且根的值相同
    //分类讨论终止: pq其中一个为空, 直接返回false; pq均为空, 则返回true
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!q && !p) return true;
        if(p && q && p->val == q->val) return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        return false; 
    }
};
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