题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean result=false;
if(root1!=null && root2!=null){
if(root1.val==root2.val){
result=DoesTree1haveTree2(root1,root2);
}
if(!result)
result=HasSubtree(root1.left,root2) || HasSubtree(root1.right,root2);
}
return result;
}
public boolean DoesTree1haveTree2(TreeNode proot1,TreeNode proot2){
if(proot2==null) return true;
if(proot1==null) return false;
if(proot1.val==proot2.val)
return DoesTree1haveTree2(proot1.left,proot2.left) && DoesTree1haveTree2(proot1.right,proot2.right);
else
return false;
}
}
代码第15、16行:
if(proot2==null) return true;
if(proot1==null) return false;
15行的这种情况是当B树的子树为空时,不管A树有没有子树直接返回true,因为到此时为止,之前的比较都是依次数值相同的。
16行的这种情况时当B树不为空,而A树已经为空的情况下,直接返回false,很明显B树不可能为A的子结构了。
LintCode通过:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param T1: The roots of binary tree T1.
* @param T2: The roots of binary tree T2.
* @return: True if T2 is a subtree of T1, or false.
*/
public boolean isSubtree(TreeNode T1, TreeNode T2) {
// write your code here
if(T2==null) return true;
if(T1==null) return false;
if(DoesTree1Tree2Same(T1,T2)){
return true;
}
if(isSubtree(T1.left,T2) || isSubtree(T1.right,T2)){
return true;
}
return false;
}
//判断两树是否完全相同
public boolean DoesTree1Tree2Same(TreeNode T1,TreeNode T2){
if(T1==null || T2==null)
return T1==T2;
if(T1.val==T2.val)
return DoesTree1Tree2Same(T1.left,T2.left) && DoesTree1Tree2Same(T1.right,T2.right);
else
return false;
}
}