以下は、 Stack を使用せずに二分探索木を順番にトラバースする反復アルゴリズムです (first left child
、次にparent
、finally )。right child
(アイデア:全体のアイデアは、ツリーの一番左の子を見つけ、手元にあるノードの後継者を毎回見つけて、ノードがなくなるまでその値を出力することです。)
void In-Order-Traverse(Node root){
Min-Tree(root); //finding left-most child
Node current = root;
while (current != null){
print-on-screen(current.key);
current = Successor(current);
}
return;
}
Node Min-Tree(Node root){ // find the leftmost child
Node current = root;
while (current.leftChild != null)
current = current.leftChild;
return current;
}
Node Successor(Node root){
if (root.rightChild != null) // if root has a right child ,find the leftmost child of the right sub-tree
return Min-Tree(root.rightChild);
else{
current = root;
while (current.parent != null && current.parent.leftChild != current)
current = current.parent;
return current.parrent;
}
}
このアルゴリズムの時間計算量は、BST にノードTheta(n)
があることを前提としていると主張されていますがn
、これは確かに正しいです。ただし、一部のノードは、サブツリー内のノードの数に依存する一定の回数を超えてトラバースされ、これらすべての訪問回数を合計しても時間の複雑さにはならないので、納得できません。Theta(n)
それを証明する方法についてのアイデアや直感はありますか?