【试题描述】定义一个函数,输入判断一个树是否是另一个对的子树
You have two very large binary trees: T1, with millions of nodes, and T2, with hun-dreds of nodes Create an algorithm to decide if T2 is a subtree of T1
Note that the problem here specifies that T1 has millions of nodes—this means that we should be careful of how much space we use Let’s say, for example, T1 has 10 million nodes—this means that the data alone is about 40 mb We could create a string representing the inorder and preorder traversals If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a sub-string of T1 We can check this using a suffix tree However, we may hit memory limitations because suffix trees are extremely memory intensive If this become an issue, we can use an alternative approach Alternative Approach: The treeMatch procedure visits each node in the small tree at most once and is called no more than once per node of the large tree Worst case runtime is at most O(n * m), where n and m are the sizes of trees T1 and T2, respectively If k is the number of occurrences of T2’s root in T1, the worst case runtime can be characterized as O(n + k * m)
【参考代码】
1 boolean containsTree(Node t1, Node t2) 2 { 3 if (t2 == null) 4 return true; 5 else 6 return subTree(t1, t2); 7 } 8 9 boolean subTree(Node r1, Node r2) 10 { 11 if (r1 == null) 12 return false; 13 if (r1.value == r2.value) 14 { 15 if (matchTree(r1, r2)) 16 return true; 17 } 18 return (subTree(r1.left,r2) || subTree(r1.right,r2)); 19 } 20 21 boolean matchTree(Node r1, Node r2) 22 { 23 if (r2 == null && r1 == null) 24 return true; 25 if (r1 == null || r2 == null) 26 return false; 27 if (r1.value != r2.value) 28 return false; 29 return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right)); 30 }