输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(!pRoot1 || !pRoot2) return false;
bool result=false;
if(pRoot1->val == pRoot2->val)result=isSubtree(pRoot1,pRoot2); // 找到判断子树
if(!result) result=HasSubtree(pRoot1->left,pRoot2); // 未找到匹配的根节点以及匹配的子树,则继续向下递归
if(!result) result=HasSubtree(pRoot1->right,pRoot2);
return result;
}
bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(!pRoot2) return true; // 子树遍历完成(关键语句)
if(!pRoot1) return false; // 主树异常时的输出(关键语句:提高鲁棒性)
bool result=true;
if(pRoot1->val!=pRoot2->val) result=false;
if(result) result=isSubtree(pRoot1->left,pRoot2->left);
if(result) result=isSubtree(pRoot1->right,pRoot2->right);
return result;
}
};
利用好短路特性,完全不用那么多flag
class Solution {
bool isSubtree(TreeNode* pRootA, TreeNode* pRootB) {
if (pRootB == NULL) return true;
if (pRootA == NULL) return false;
if (pRootB->val == pRootA->val) {
return isSubtree(pRootA->left, pRootB->left)
&& isSubtree(pRootA->right, pRootB->right);
} else return false;
}
public:
bool HasSubtree(TreeNode* pRootA, TreeNode* pRootB)
{
if (pRootA == NULL || pRootB == NULL) return false;
return isSubtree(pRootA, pRootB) ||
HasSubtree(pRootA->left, pRootB) ||
HasSubtree(pRootA->right, pRootB);
}
};