原文:
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1
译文:
有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写程序判断T2是否为T1的子树。
思路:
1) 因为中序前序遍历就可以决定一棵树,把两棵树的中序前序都写出来,如果两个遍历中T2都是T1的子串,可以确定T2是T1的子树。
当然这会遇到无法区分
的情况。因为
T1, in order: 3,3 T1, pre order 3,3
T2, in order: 3,3 T2, pre order 3,3
所以必须也算入null节点,所以
T1, in order: 0, 3, 0, 3, 0 T1, pre order 3, 3, 0, 0, 0
T2, in order: 0, 3, 0, 3, 0 T2, pre order 3, 0, 3, 0, 0
这种方法时间复杂度:O(n+m), 空间复杂度:O(n+m) , n,m分别为两个树的节点数。当海量数据时不适用!
2)递归!从根节点往下递归,判断子树是否存在其的左子树或右子树内。
时间复杂度:
O(nm), 空间复杂度:
O(log(n) + log(m))
但实际上,在真实的运行时,递归假如发现满足子树的条件就直接返回,而不会继续查找。因此递归法在实际中无论时间空间更优!
package Tree_Graph;
import CtCILibrary.AssortedMethods;
import CtCILibrary.TreeNode;
public class S4_8 {
// 判断t2是否是t1的子树
public static boolean isSubTree(TreeNode t1, TreeNode t2) {
if(t2 == null) { // 空树始终是另一个树的子树
return true;
}
if(t1 == null) { // 此时r2非空,非空树不可能是一个空树的子树
return false;
}
if(t1.data == t2.data) { // 找到两树匹配
if(isSameTree(t1, t2)){
return true;
}
}
// 继续在r1的左子树和右子树里找匹配
return isSubTree(t1.left, t2) || isSubTree(t1.right, t2);
}
// 判断两棵树是否相同
public static boolean isSameTree(TreeNode t1, TreeNode t2) {
if(t1==null && t2==null) {
return true;
}
if(t1==null || t2==null) {
return false;
}
if(t1.data != t2.data) {
return false;
}
return isSameTree(t1.left, t2.left) && isSameTree(t1.right, t2.right);
}
public static void main(String[] args) {
// t2 is a subtree of t1
int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int[] array2 = {2, 4, 5, 8, 9, 10, 11};
TreeNode t1 = AssortedMethods.createTreeFromArray(array1);
TreeNode t2 = AssortedMethods.createTreeFromArray(array2);
if (isSubTree(t1, t2))
System.out.println("t2 is a subtree of t1");
else
System.out.println("t2 is not a subtree of t1");
// t4 is not a subtree of t3
int[] array3 = {1, 2, 3};
TreeNode t3 = AssortedMethods.createTreeFromArray(array1);
TreeNode t4 = AssortedMethods.createTreeFromArray(array3);
if (isSubTree(t3, t4))
System.out.println("t4 is a subtree of t3");
else
System.out.println("t4 is not a subtree of t3");
}
}