Likou 572: A Subtree of Another Tree

insert image description here
When doing this question, we think that the subtree of another tree is the subtree of the parent tree that is the same as that tree,
which is the judgment of the same tree.
insert image description here
insert image description here
Next, we write code according to the judgment.

class Solution {
    
    

 private boolean isSameTree(TreeNode p, TreeNode q) {
    
      //判断两颗树是不是相同
        if(p == null && q == null){
    
    
            return true;
        }
if(p == null && q != null || p != null && q == null){
    
    
    return false;
}
if(p.val != q.val){
    
    
    return false;
}
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);  //这边是返回true or false
    }

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
    
    
if(root == null || subRoot == null){
    
      //父树为空 或 子树为空 单项条件都不行
    return false;
}
if(isSameTree(root,subRoot)){
    
      //两颗树相同,返回true
    return true;
}
if(isSubtree(root.left,subRoot)){
    
      //递归父树的左子树跟subRoot比较
    return true;
}
if(isSubtree(root.right,subRoot)){
    
    
    return true;
}
return false;  //左右都没有,返回false
    }
}

Link: A subtree of another tree!

Guess you like

Origin blog.csdn.net/chenbaifan/article/details/123601151