572.Subtree of Another Tree
572.Subtree of Another Tree
难度:Easy
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
1
Example 1:
2
Given tree s:
3
4
3
5
/ \
6
4 5
7
/ \
8
1 2
9
Given tree t:
10
4
11
/ \
12
1 2
13
Return true, because t has the same structure and node values with a subtree of s.
14
Example 2:
15
Given tree s:
16
17
3
18
/ \
19
4 5
20
/ \
21
1 2
22
/
23
0
24
Given tree t:
25
4
26
/ \
27
1 2
28
Return false.
Copied!
需要子树的要求,在子树到达叶子节点的时候,原数也是叶子节点。
1
/**
2
* Definition for a binary tree node.
3
* struct TreeNode {
4
* int val;
5
* TreeNode *left;
6
* TreeNode *right;
7
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
* };
9
*/
10
class Solution {
11
bool isEqual(TreeNode*s,TreeNode*t){
12
if(!t) return s? false :true;
13
if(!s) return false;
14
if(s->val != t->val) return false;
15
return isEqual(s->left,t->left) && isEqual(s->right,t->right);
16
}
17
public:
18
bool isSubtree(TreeNode* s, TreeNode* t) {
19
if(!s && !t) return true;
20
if(!s || !t) return false;
21
if(s->val == t->val && isEqual(s,t)) return true;
22
return isSubtree(s->left,t) || isSubtree(s->right,t);
23
24
}
25
};
Copied!
执行用时 :36 ms, 在所有 C++ 提交中击败了86.12%的用户 内存消耗 :21 MB, 在所有 C++ 提交中击败了77.88%的用户
Copy link