2-3 ツリーのイテレータについて助けが必要でした。私が現在実装している方法は、DFS にほぼ似た再帰的アプローチです。ルートからトラバーサルを初期化し、リーフ ノードに到達するまで左側のブランチにアクセスし、それを Linked-List に追加します。再帰がバックトラックするにつれて、左のブランチのすべてのノードが追加され、次にルートの最初のキーが順序を維持するために追加されます。真ん中と右の枝でも同じことをします。リンク リストが作成されたら、そのイテレータを返すだけです。私が知りたかったのは、これが 2-3 ツリーのイテレータを構築する最良の方法ですか? 効率的にするために何を変更できますか?ツリーが巨大化すると、再帰呼び出しで StackOverFlowError が発生するのではないかと心配しています (笑、皮肉です)。
private class Traversal
{
LinkedList<Node> ordered;
void traverseTree()
{
ordered = new LinkedList<>(); // Reset the ordered list. traverseTree will be only called in case of modification
traverse(root); // Initialize traversal from the root.
}
void traverse(Node n)
{
if (n.children.size() == 0) // If it's a leaf node, add it to the linked list.
ordered.add(n);
else
{
traverse(n.children.get(0)); // Otherwise, first traverse the left branch
ordered.add(new Node(n.keys.get(0))); // When it is done, create a new node containing key 1 of the node n to keep it ordered.
traverse(n.children.get(1)); // Then traverse the middle/right branch of n.
if (n.children.size() == 3) // If there are 3 branches, then we still need to traverse it.
{
ordered.add(new Node(n.keys.get(1))); // Before we traverse, create a new node containing the 2nd key of n to the list since everything is going to be greater than it in the right branch.
traverse(n.children.get(2)); // Then traverse the last branch and add all encountered nodes in order.
}
}
}
}