CodingInterview-树的子结构

思路比较显而易见,首先在 pRoot1 中寻找和 pRoot2 相同的节点,然后判断这两个节点下方的树是否相同。

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
/*
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)
{
if(pRoot1==NULL || pRoot2==NULL) return false;
if((pRoot1->val==pRoot2->val)&&(IsSubTree(pRoot1,pRoot2)))
return true;
return HasSubtree(pRoot1->left,pRoot2)
|| HasSubtree(pRoot1->right,pRoot2);
}
bool IsSubTree(TreeNode* pRoot1,TreeNode* pRoot2){
if(pRoot2==NULL) return true;
if(pRoot1==NULL) return false;
if(pRoot1->val!=pRoot2->val) return false;
return IsSubTree(pRoot1->left,pRoot2->left)
&& IsSubTree(pRoot1->right,pRoot2->right);
}
};