如下图所示,则认为树B是树A的子树。
代码如下:
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { //判断root2是否是root1的子树 public boolean HasSubtree(TreeNode root1,TreeNode root2) { if(root1 ==null || root2==null) return false; if(isEqualTree(root1,root2)){ return true; }else{ return HasSubtree(root1.left,root2) || HasSubtree(root1.right,root2); } } //判断B是否是A的子树,并且从根节点开始,即A.val=B.val public boolean isEqualTree(TreeNode A,TreeNode B){ if(B==null) return true; if(A==null) return false; if(A.val != B.val) return false; return isEqualTree(A.left,B.left) && isEqualTree(A.right,B.right); } }
时间: 2024-11-25 04:25:52