0%

subtree-of-another-tree

Subtree of Another Tree – LeetCode 572

Problem

Description

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.

Answer

Original

Code

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
/**
* 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 {
private:
bool check(TreeNode *s, TreeNode *t){
if(s && t){
if(s->val == t->val)
return check(s->left, t->left) && check(s->right, t->right);
else
return false;
} else if(!s && !t)
return true;
else
return false;
}
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(s && t){
if(s->val == t->val && check(s, t))
return true;
else
return isSubtree(s->left, t) || isSubtree(s->right, t);
} else
return false;
}
};

思路

优先寻找潜在子树头,找到后使用check检查。时间复杂度$O(m \times n)$,空间复杂度$O(m)$。
耗时$16$ ms,排名$5.75\%$

Better

思路

还没看到更好的思路。