- 该题的思路应该使用递归来判断,通过判断左子树和右子树来判断树是否是子结构,当子结构为空时,则判断成功
import javax.swing.tree.TreeNode;
public class childTree {
public boolean HasSubtree(TreeNode root1,TreeNode root2){
boolean result = false;
if(root1==null&&root2==null) return true;
if(root1==null) return false;
if(root1.val==root2.val){
result = isSubtree(root1,root2);
}
if(!result)
HasSubtree(root1.left,root2);
if(!result)
HasSubtree(root2.right,root2);
return result;
}
public boolean isSubtree(TreeNode root1,TreeNode root2){
if(root2==null)
return true;
if(root1==null)
return false;
if(roo1.val!=root2.val)
return false;
else
return isSubtree(root1.left,root2.left)&&isSubtree(root1.right,root2.right);
}
}