0%

面试题 04.10. 检查子树

面试题 04.10. 检查子树

递归
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
/**
* 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 {
public:
bool checkSubTree(TreeNode* t1, TreeNode* t2) {
queue<TreeNode*> q;
q.push(t1);
while(!q.empty())
{
auto p = q.front();
q.pop();
if(check(p, t2))
return true;
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
return false;
}
private:
bool check(TreeNode* t1, TreeNode* t2)
{
if(!t1)
return !t2;
if(!t2)
return !t1;
if(t1->val != t2->val)
return false;
return check(t1->left, t2->left) && check(t1->right, t2->right);
}
};

递归改

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
/**
* 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 {
public:
bool checkSubTree(TreeNode* t1, TreeNode* t2) {
if(!t1)
return !t2;
return check(t1, t2) || checkSubTree(t1->left, t2) || checkSubTree(t1->right, t2);
}
private:
bool check(TreeNode* t1, TreeNode* t2)
{
if(!t1)
return !t2;
if(!t2)
return !t1;
if(t1->val != t2->val)
return false;
return check(t1->left, t2->left) && check(t1->right, t2->right);
}
};