题目链接:572. 另一棵树的子树
二叉树遍历综合问题
题意
给定两棵树,判断第二棵树是否为第一颗树的子树。
思路
用到了100. 相同的树 的思路,把给定的二叉树,每个节点都和subRoot都做一次相同的树的比较,只要正确,就返回true。
AC Code:
bool issamtree(TreeNode* root1, TreeNode* root2)//相同树的比较
{
if (root1 == NULL && root2 == NULL)
{
return true;
}
if (root1 == NULL || root2 == NULL || root1->val != root2->val)
{
return false;
}
return issamtree(root1->left, root2->left) && issamtree(root1->right, root2->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (root == NULL)
{
return false;
}
if (issamtree(root, subRoot))//只要有相同的就返回true
{
return true;
}
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);//遍历给定的树
}