剑指offer:面试题18——树的子结构
题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool DoesTreeHaveTree2(TreeNode *pRoot1,TreeNode*pRoot2)
{
if(pRoot2==NULL) //树2到达叶子节点
return true;
if(pRoot1==NULL) //树1到达叶子节点
return false;
if(pRoot1->val!=pRoot2->val)
return false;
return DoesTreeHaveTree2(pRoot1->left,pRoot2->left)&&DoesTreeHaveTree2(pRoot1->right,pRoot2->right);
}
public:
bool FindRoot(TreeNode *pRoot1,TreeNode*pRoot2)
{
bool result =false;
if(pRoot2!=NULL && pRoot1!=NULL)
{
if(pRoot1->val==pRoot2->val)
result=DoesTreeHaveTree2(pRoot1,pRoot2);
if(!result)
result=FindRoot(pRoot1->left,pRoot2);
if(!result)
result=FindRoot(pRoot1->right,pRoot2);
}
return result;
}
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
return FindRoot(pRoot1,pRoot2);
}
};