-
Notifications
You must be signed in to change notification settings - Fork 28
/
Subtree_of_Another_Tree.cpp
57 lines (54 loc) · 1.62 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* 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 {
bool isSameTree(TreeNode* s, TreeNode* t) {
if(!s and !t) return true;
if(!s or !t) return false;
return s->val == t->val and isSameTree(s->left, t->left) and isSameTree(s->right, t->right);
}
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(s == nullptr) return false;
return isSameTree(s, t) or isSubtree(s->left, t) or isSubtree(s->right, t);
}
};
// using preorder hash (postorder or inorder also works)
class Solution {
string preorderHash(TreeNode* root) {
if(!root) {
return "#";
}
return to_string(root->val)
+ "," + preorderHash(root->left)
+ "," + preorderHash(root->right);
}
string checkSubtree(TreeNode* root, string const& signature, bool& isSubtree) {
if(!root) {
return "#";
}
if(isSubtree) {
return "";
}
string preorder = to_string(root->val);
preorder += "," + checkSubtree(root->left, signature, isSubtree);
preorder += "," + checkSubtree(root->right, signature, isSubtree);
if(preorder == signature) {
isSubtree = true;
}
return preorder;
}
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
string signature = preorderHash(t);
bool isSubtree = false;
checkSubtree(s, signature, isSubtree);
return isSubtree;
}
};