Skip to content

Commit 108fff0

Browse files
committed
Runtime: 90 ms (Top 5.5%) | Memory: 37.50 MB (Top 5.0%)
1 parent 83466af commit 108fff0

File tree

1 file changed

+68
-9
lines changed

1 file changed

+68
-9
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,72 @@
1+
// Runtime: 90 ms (Top 5.5%) | Memory: 37.50 MB (Top 5.0%)
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* struct TreeNode {
6+
* int val;
7+
* TreeNode *left;
8+
* TreeNode *right;
9+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
10+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12+
* };
13+
*/
114
class Solution {
215
public:
16+
void sol(TreeNode *root, string &s){
17+
queue<TreeNode*> q;
18+
q.push(root);
19+
s+=to_string(root->val);
20+
while(!q.empty()){
21+
auto x=q.front(); q.pop();
22+
if(x->left){
23+
24+
s+=to_string( x->left->val);
25+
q.push(x->left);
26+
}else if(!x->left){
27+
s+='#';
28+
}
29+
if(x->right){
30+
s+=to_string( x->right->val);
31+
q.push(x->right);
32+
}else if(!x->right){
33+
s+='#';
34+
}
35+
36+
}
37+
}
338
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
4-
string s1 = convertToString(root);
5-
string s2 = convertToString(subRoot);
6-
return s1.find(s2) != string::npos;
39+
40+
string s;
41+
sol(subRoot, s);
42+
cout<<s<<" ";
43+
queue<TreeNode*> q;
44+
q.push(root);
45+
while(!q.empty()){
46+
auto x=q.front(); q.pop();
47+
if(x->val==subRoot->val){
48+
string k;
49+
sol(x, k);
50+
cout<<k<<" ";
51+
bool istrue=false;
52+
if(k.size()==s.size()){
53+
for(int i=0; i<k.size(); i++){
54+
if(k[i]!=s[i]){
55+
istrue=true;
56+
}
57+
}
58+
if(istrue==false){
59+
return true;
60+
}
61+
}
62+
}
63+
if(x->left){
64+
q.push(x->left);
65+
}
66+
if(x->right){
67+
q.push(x->right);
68+
}
69+
}
70+
return false;
771
}
8-
9-
string convertToString(TreeNode* node) {
10-
if(node == NULL) return "NULL,";
11-
return "[" + to_string(node->val) + "]" + "," + convertToString(node->left) + convertToString(node->right);
12-
}
13-
};
72+
};

0 commit comments

Comments
 (0)