Skip to content

[LeetCode] 100. 相同的树 #27

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
Animenzzzz opened this issue Aug 7, 2019 · 0 comments
Open

[LeetCode] 100. 相同的树 #27

Animenzzzz opened this issue Aug 7, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

示例 3:

输入:       1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false

解题思路:结构相同:同时为空;节点值相同。否则返回空。树的题目要理解一下递归。。。这个思想太尼玛重要了,学习中学习中。。。

C解题:

bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if(!p && !q) return true;
    if(!p || !q) return false;
    if(p->val != q->val) return false;
    return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant