/*
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)
{
bool bIsInclude = false;
//边界条件
if (NULL == pRoot1 || NULL == pRoot2)//表示结点为NULL,表示某条路径遍历结束,均不匹配。
{
return false;
}
//判断根节点
if (pRoot1->val == pRoot2->val)
{
bIsInclude = IsInclude(pRoot1,pRoot2);
}
//判断左右子树是否匹配,但是在父亲已经匹配时,不用继续比较了
if (!bIsInclude)
{
bIsInclude = HasSubtree(pRoot1->left, pRoot2);
}
if (!bIsInclude)
{
bIsInclude = HasSubtree(pRoot1->right, pRoot2);
}
return bIsInclude;
}
bool IsInclude(TreeNode* pRootTarget,TreeNode* pRootPattern)
{
if (NULL == pRootPattern)//模式树为空,匹配成功
{
return true;
}
if (NULL == pRootTarget)//模式树不为空,主树为空,不匹配
{
return false;
}
if (pRootTarget->val != pRootPattern->val)
{
return false;
}
return IsInclude(pRootTarget->left,pRootPattern->left)
&& IsInclude(pRootTarget->right,pRootPattern->right);
}
};
树的子结构
最新推荐文章于 2020-05-12 17:06:50 发布