Given two binary trees, check if the first tree is subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.
两个树,先写另一个函数:isIdentical,
用递归的方式:如何判断两个树是否完全一样呢?那就看从根开始,所有节点的值都相等。
写好了这个,就简单了。 给两个树的根,如何都相等,root就是root2的子树,反之,我们还要查看其他节点,要检查的子树root不变,看left和right树。
继续递归,只要找到一个相等的,那就是有子树。思路其实很简单,就是不要把这个问题放到一个递归里,比较麻烦。 我要是放一起考虑,就感觉会脑残。
public static boolean isSubTree(TreeNode root,TreeNode root2){
if(root==null) return true;
if(root2==null) return false;
if(isIdentical(root,root2)) return true;
else {
return isIdentical(root,root2.left)||isIdentical(root,root2.right);
}
}
public static boolean isIdentical(TreeNode root,TreeNode root2){
if(root==null&&root2==null) return true;
if(root==null||root2==null) return false;
if(root.val==root2.val) {
return isSubTree(root.left,root2.left)&&isSubTree(root.right,root2.right);
}
else return false;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val=x;
}
}
主函数test case:
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root=new TreeNode(10);
root.left=new TreeNode(4);
root.right=new TreeNode(6);
root.left.right=new TreeNode(30);
TreeNode root2=new TreeNode(26);
root2.left=new TreeNode(10);
root2.left.left=new TreeNode(4);
root2.left.right=new TreeNode(6);
root2.right=new TreeNode(6);
root2.left.left.right=new TreeNode(30);
root2.right=new TreeNode(3);
root2.right.right=new TreeNode(3);
System.out.println(isSubTree(root,root2));
//System.out.println(isIdentical(root,root2));
}