forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubtree-of-another-tree.cpp
37 lines (34 loc) · 975 Bytes
/
subtree-of-another-tree.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
34
35
36
37
// Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t
// Space: O(h), h is the height of s
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
return preOrderTraverse(s, t);
}
private:
bool preOrderTraverse(TreeNode *s, TreeNode *t) {
return s && (isSame(s, t) ||
preOrderTraverse(s->left, t) ||
preOrderTraverse(s->right, t));
}
bool isSame(TreeNode *x,TreeNode *y) {
if (!x && !y) {
return true;
}
if (!x || !y) {
return false;
}
return x->val == y->val &&
isSame(x->left, y->left) &&
isSame(x->right, y->right);
}
};