-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsubtree_of_another_tree.cpp
More file actions
80 lines (73 loc) · 2.18 KB
/
subtree_of_another_tree.cpp
File metadata and controls
80 lines (73 loc) · 2.18 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Subtree of another Tree
* Problem: https://leetcode.com/problems/subtree-of-another-tree/
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
inline vector<TreeNode*> get_candidates(TreeNode *root, int value) {
stack<TreeNode*> st;
st.push(root);
vector<TreeNode*> roots;
while (!st.empty()) {
TreeNode *u = st.top(); st.pop();
if (u->val == value) {
roots.push_back(u);
}
if (u->left != nullptr) {
st.push(u->left);
}
if (u->right != nullptr) {
st.push(u->right);
}
}
return roots;
}
inline bool match(TreeNode *a, TreeNode *b) {
stack<TreeNode*> st_a, st_b;
st_a.push(a); st_b.push(b);
while (!st_a.empty() && !st_b.empty()) {
TreeNode *u = st_a.top(); st_a.pop();
TreeNode *v = st_b.top(); st_b.pop();
if (u->val != v->val || ((u->left == nullptr) ^ (v->left == nullptr))
|| ((u->right == nullptr) ^ (v->right == nullptr))) {
return false;
}
if (u->left != nullptr) {
st_a.push(u->left);
st_b.push(v->left);
}
if (u->right != nullptr) {
st_a.push(u->right);
st_b.push(v->right);
}
}
return st_a.empty() && st_b.empty();
}
public:
bool isSubtree(TreeNode *s, TreeNode *t) {
if ((s == nullptr) ^ (t == nullptr)) {
return false;
}
if (s == nullptr && t == nullptr) {
return true;
}
vector<TreeNode*> roots = get_candidates(s, t->val);
for (TreeNode *root : roots) {
if (match(root, t)) {
return true;
}
}
return false;
}
};