-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path572.cpp
60 lines (60 loc) · 1.32 KB
/
572.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// preorder.cpp
/**
* 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) {
if (s == NULL)
return t == NULL;
if (t == NULL)
return false;
bool res = 0;
if (s->val == t->val)
res = isSame(s, t);
return res || isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool isSame(TreeNode *s, TreeNode *t) {
if (s == NULL)
return t == NULL;
if (t == NULL)
return s == NULL;
return s->val == t->val && isSame(s->left, t->left) &&
isSame(s->right, t->right);
}
};
// preorder2.cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution2 {
public:
bool isSubtree(TreeNode *s, TreeNode *t) {
string ss, tt;
preorder(s, ss);
preorder(t, tt);
return ss.find(tt) != std::string::npos;
}
void preorder(TreeNode *root, string &s) {
s += ",";
if (root == NULL) {
s += "#";
return;
}
s += to_string(root->val);
preorder(root->left, s);
preorder(root->right, s);
}
};