-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path572. Subtree of Another Tree.cpp
35 lines (35 loc) · 1.12 KB
/
572. 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
/**
* 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 {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!subRoot) return true;
string subserial = serialize(subRoot);
bool res = false;
dfs(root,subserial,res);
return res;
}
string serialize(TreeNode* root) {
if (!root) return "";
return to_string(root->val) + "," + serialize(root->left) + "," + serialize(root->right);
}
string dfs(TreeNode* root, string &subserial, bool &res) {
if (res) return "";
if (!root) return "";
string curr = to_string(root->val) + "," + dfs(root->left, subserial, res) + "," + dfs(root->right, subserial, res);
if (curr == subserial) {
res = true;
return "";
}
return curr;
}
};