-
Notifications
You must be signed in to change notification settings - Fork 1
/
572Subtree.cpp
33 lines (31 loc) · 1016 Bytes
/
572Subtree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 错误的:
// runtime error: member access within null pointer of type xxx
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (!s && !t) return false;
if (sameTree(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool sameTree(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t) return false;
if (s->val != t->val) return false;
return sameTree(s->left, t->left) && sameTree(s->right, t->right);
}
};
// this works
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (!s) return false;
if (sameTree(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool sameTree(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t) return false;
if (s->val != t->val) return false;
return sameTree(s->left, t->left) && sameTree(s->right, t->right);
}
};