首页 > 代码库 > 树的子树

树的子树

判断一棵树是否是另一棵树的子树

public class Solution {    public boolean HasSubtree(TreeNode root1,TreeNode root2) {        boolean result = false;        if(root1 == null || root2 == null) return false;        if(root1!=null && root2!=null){            if(root1.val == root2.val){                result = SameTree(root1,root2);            }            if(!result){                result = HasSubtree(root1.left,root2);            }            if(!result){                result = HasSubtree(root1.right,root2);            }        }        return result;    }    public boolean SameTree(TreeNode root1,TreeNode root2){        if(root1 == null && root2 == null){            return true;        }        if(root1 == null &&root2!=null){            return false;        }        if(root1!=null && root2 == null){ //子树就是两棵树都到头时才能返回真            return false;        }        if(root1.val != root2.val){            return false;        }        return SameTree(root1.left,root2.left)&&SameTree(root1.right,root2.right);    }    }

 

树的子树