【发布时间】:2015-06-07 04:49:33
【问题描述】:
这个问题来自Cracking the Coding Interview一书。我无法理解解决方案的空间复杂度。
问题:
你有两棵非常大的二叉树:T1,有数百万个节点,T2,有数百个节点。创建一个算法来确定 T2 是否是 T1 的子树。
解决方案(Java):
public static boolean containsTree(TreeNode t1, TreeNode t2) {
if (t2 == null)
return true; // The empty tree is a subtree of every tree.
else
return subTree(t1, t2);
}
/* Checks if the binary tree rooted at r1 contains the binary tree
* rooted at r2 as a subtree somewhere within it.
*/
public static boolean subTree(TreeNode r1, TreeNode r2) {
if (r1 == null)
return false; // big tree empty & subtree still not found.
if (r1.data == r2.data) {
if (matchTree(r1,r2)) return true;
}
return (subTree(r1.left, r2) || subTree(r1.right, r2));
}
/* Checks if the binary tree rooted at r1 contains the
* binary tree rooted at r2 as a subtree starting at r1.
*/
public static boolean matchTree(TreeNode r1, TreeNode r2) {
if (r2 == null && r1 == null)
return true; // nothing left in the subtree
if (r1 == null || r2 == null)
return false; // big tree empty & subtree still not found
if (r1.data != r2.data)
return false; // data doesn’t match
return (matchTree(r1.left, r2.left) &&
matchTree(r1.right, r2.right));
}
书上说这个解决方案的空间复杂度是O(log(n) +log(m)),其中m是节点数T1(更大的树)和T2中的n个节点。
对我而言,似乎解决方案具有 O(log(m)*log(n)) 空间复杂度,因为“子树”函数具有 log(n)递归调用,每个递归调用执行“matchTree”函数,触发 log(m) 递归调用。
为什么这个解是 O(log(n) + log(m)) 复杂度?
【问题讨论】:
标签: java algorithm binary-tree space-complexity