LeetCode | 572. Subtree of another tree

LeetCode | 572. Subtree of another tree

OJ link

Insert image description here

  • We need to judge whether two binary trees are the same. If they are different when judging, we will directly return false, otherwise we will return true.
  • Then check whether there is a subRoot subtree in the left subtree and right subtree~~
bool isSameTree(struct TreeNode* q, struct TreeNode* p)
{
    
    
    if(q == NULL && p == NULL)
        return true;
    if(q == NULL || p == NULL)
        return  false;
    if(q->val != p->val)
        return false;
    return isSameTree(q->left,p->left)
        && isSameTree(q->right,p->right);
}

bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){
    
    
    if(root == NULL)
        return NULL;
    
    if(isSameTree(root,subRoot))
        return true;
    
    return isSubtree(root->left,subRoot)
        || isSubtree(root->right,subRoot);
}

Guess you like

Origin blog.csdn.net/2201_76004325/article/details/134767852