-
Notifications
You must be signed in to change notification settings - Fork 0
/
17.HasSubtree.cpp
64 lines (57 loc) · 1.29 KB
/
17.HasSubtree.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 数的子结构
* nowcoder:https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
* */
#include <iostream>
/*
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) :
* val(x), left(NULL), right(NULL) {
* }
* };
* */
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2);
private:
bool assist(TreeNode* pRoot1, TreeNode* pRoot2);
};
bool Solution::HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
// 空树不是任意一个树的子结构
if (!pRoot1 || !pRoot2)
{
return false;
}
return assist(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
}
bool Solution::assist(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (!pRoot2)
{
return true;
}
if(!pRoot1)
{
return false;
}
if(pRoot1->val == pRoot2->val)
{
return assist(pRoot1->left, pRoot2->left) && assist(pRoot1->right, pRoot2->right);
}
else
{
return false;
}
}