ノード (BST 内) が次のように定義されているとします (すべてのセッター/ゲッター/初期化を無視します)。
class Node
{
Node parent;
Node leftChild;
Node rightChild;
int value;
// ... other stuff
}
Node
BST ( と呼ばれるstartNode
) と別のNode
( と呼ばれる) のsome への参照が与えられた場合、target
を含むツリーに に等しいstartNode
ノードがあるかどうかを確認します。value
target.value
これを行うには、次の 2 つのアルゴリズムがあります。
アルゴリズム #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)
(これは、数学のほとんどを忘れてしまったので、私が得ることができる最高の見積もりです!)
だから私は2つの質問があります:
0) What is the time-complexity of algorithm #2 in terms of n
1) Which algorithm does better in term of time-complexity?