4.8

来源:互联网 发布:软件培训要好多钱 编辑:程序博客网 时间:2024/06/05 11:51

Topic 4.8 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. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

方法1:If data set is small, we can do a traversal, and call isSubstring method, remember to mark the null value, so that left-tree and right-tree can be distinguished. Additional Memory O(n+m) is needed. n is the number of nodes for T1, m is the number of nodes for T2.

方法2:Search through the large tree, each time a node in T1 matches the root of T2, call treeMatch. Time: O(nm), but can have a tighter bound.

1) treeMatch is not called on every node in T1, we call it k times, k is the number of occurrences of T2’s root in T1. So O(n+km)

2)Even if roots are same, if there is a difference, we exit and do not actually llok at all m nodes.

public class c4_8 {//分开来写的好处在于:r2==null只用判断一次,如果放在下面的方法了,递归要调用很多次public static boolean containsTree(TreeNode r1, TreeNode r2) {if (r2 == null)return true; elsereturn subTree(r1, r2);}//此方法只考虑从T1的上面往下面扫描public static boolean subTree(TreeNode r1, TreeNode r2) {    if (r1 == null)return false; // big tree empty & subtree still not found.else if (r1.data == r2.data) {if (matchTree(r1,r2)) return true;}return (subTree(r1.left, r2) || subTree(r1.right, r2)); }public static boolean matchTree(TreeNode r1, TreeNode r2) {if (r2 == null && r1 == null) return true; // nothing left in the subtreeif (r1 == null || r2 == null) return false;//这里必须这样写,因为此方法要递归向下,要考虑r1和r2的终止条件,就是底下为null的情况。否则会NullPointerExceptionif (r1.data != r2.data) return false; return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));}public static void main(String[] args) {int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int[] array2 = {3,4};TreeNode r1=TreeNode.createMinimalBST(array1);TreeNode r2=TreeNode.createMinimalBST(array2);System.out.println(containsTree(r1,r2));}}
//结果true


原创粉丝点击