[英]Why is the runtime of this algorithm O(t)?
這是來自 Cracking the Coding Interview 6th edition 的問題 4.8。 以下代碼是以下提示的一種解決方案:“Find the first commonance of two nodes in a binary tree”
TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q){
/* Checks if either node is not in the tree, or if one covers the other. */
if(!covers(root, p) || !covers(root, q)){
return null;
} else if (covers(p,q)){
return p;
} else if (cover(q,p)){
return q;
}
/* Traverse upwards until you find a node that covers q. */
TreeNode sibling = getSibling(p);
TreeNode parent = p.parent;
while(!covers(sibling, q)){
sibling = getSibling(parent);
parent = parent.parent;
}
return parent;
}
boolean covers(TreeNode root, TreeNode p){
if(node == null) return false;
if(root == p) return true;
return covers(root.left, p) || covers(root.right,p);
}
TreeNode getSibling(TreeNode node){
if(node == null || node.parent ==null){
return null;
}
TreeNode parent = node.parent;
return parent.left == node ? parent.right: parent.left;
}
這本書說“這個算法需要 O(t) 時間,其中 t 是第一個共同祖先的子樹的大小。在最壞的情況下,這將是 O(n)”
然而,在 commonAncestor 開始時從根調用covers 不是使運行時O(d+t),d 是p 或q 的深度,這取決於哪個更深。
好吧,看起來cover(root,p)
將搜索以x
為根的整個子樹,因為它遞歸地檢查root.left
和root.right
。
但是是的,這個問題可以在 O(d) 時間內解決。 (從p
, q
中的每一個上升到根,然后只是兩個列表共有的第一個元素。)
嗯,看起來cover
里面的代碼也是錯誤的,有幾種不同的方式:
return false
而不是return null
;if (root==p) return true
。 (可以聰明地將現有的return
語句修改為return (root==p) || covers(..,..) || covers(..,..)
。)您可能需要查看本書開頭的 Big O 部分。 O(d+t) 有點准確,但因為這是一個加號,其中一個(d 或 t)會比另一個更快地變大。 在這種情況下,t = 子樹中的節點數,d = 整個樹中的深度。 T 將比 d 增長得更快。
舉例說明:
1
/ \
2 3
/ \ / \
4 5 6 7
If We're looking at this tree and we want to know the common ancestor for 4 and 5:
t = 3
d = 3
if we want the common ancestor of 2 and 7 in the same tree then:
t = 7
d = 3
由於樹的工作方式,深度將始終等於或小於節點數。 因此,時間復雜度將是 t(子樹中的節點數)的平均值(大 theta?),最壞的情況是(大 o)n(樹中的節點數)。
順便說一句,對 root 的檢查將在開始時執行 O(n),這將使整個事情 O(n),但作者指出它確實如此,實際上有 O(n)。 “這個算法需要 O(t) 時間”是,我認為,作者對平均情況的分析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.