假設節點(在BST中)定義如下(忽略所有setters/getters/inits)。以下算法的時間複雜度
class Node
{
Node parent;
Node leftChild;
Node rightChild;
int value;
// ... other stuff
}
鑑於一些在一個BST一些Node
(稱爲startNode
)和另一Node
(稱爲target
)的引用,一個是檢查含有startNode
樹是否具有其value
等於target.value
任何節點。
我有兩個算法來做到這一點:
算法#1:
- From `startNode`, trace the way to the root node (using the `Node.parent` reference) : O(n)
- From the root node, do a regular binary search for the target : O(log(n))
T(N)= O(的log(n)+ N)
算法# 2:基本上執行DFS (僅限僞代碼)
current_node = startnode
While the root has not been reached
go up one level from the current_node
perform a binary-search from this node downward (excluding the branch from which we just go up)
這個算法的時間複雜度是多少?
天真的回答會是O(n * log(n))
,其中n
對於while
循環,因爲有最多n
節點,log(n)
是二進制搜索。但顯然,這是高估方式!
最好的(部分)答案,我能想出是:
假設每個支行有一定的
m_i
節點和有k
支行。 換句話說,k
是節點startNode
之間和的總時間將是
數根節點
。
T(n) = log(m1) + log(m2) + ... + log(mk)
= log(m1 * m2 * ... * mk)
Where m1 + m2 + ... + mk = n (the total number of nodes in the tree)
(這是我能得到我忘了我的大部分數學做任何更好的最佳估計數!)
所以我有兩個問題:
0) What is the time-complexity of algorithm #2 in terms of n
1) Which algorithm does better in term of time-complexity?