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
- 4.8
- 4.8
- 4.8
- 4.8
- 4.8
- 4.8
- 4.8~4.10
- Notepad++ 4.8
- 4.8小结
- CareerCup 4.8
- Exercise 4.8
- opencv2.4.8
- 4.8 T1
- 习题4.8
- Notepad++ 4.8 RC
- Notepad++ 4.8.1
- Notepad++ 4.8.2
- LuaForS60 工程进度 4.1 --- 4.8
- FreeMaker教程
- 在O(n)时间复杂度O(1)空间复杂度求一个数组中出现多次和未出现的数字
- 8招让你更沉稳
- nginx图片缓存
- ATL7窗口类详细剖析
- 4.8
- [Mac]GCC,LLVM,Clang编译器对比
- 2013年9月28日17:54:59 code ··· merge sort ····
- 关于 写代码 2013年9月28日18:22:43
- 算法导论公开课对应章节(来自MIT)
- Linux的I2C 设备驱动 -- mini2440 上i2c接口触摸屏驱动
- Java中Java.util.Date无法导入的问题
- 那些程序员教给我的------爱情的本质是相互欣赏
- 英语对于软件开发者来说到底有多重要?