首页 > 解决方案 > B树的深度优先搜索

问题描述

我有一个 B 树,我目前可以使用递归中序遍历对其进行迭代。但是,我需要不递归地迭代。我尝试了各种方法,最接近的是使用深度优先搜索。我已成功打印树中的所有元素,但顺序不正确。我确实理解为什么它没有按顺序排列,但我不明白如何修复它。这就是我得到的:

public void iterative() {
            Stack<BTreeNode<T>> stack = new Stack<>();
            stack.push(this);
            while(!stack.empty()) {
                BTreeNode<T> curr = stack.pop();

                int i;
                for (i = 0; i < curr.numNodes; i++) {

                    if (!curr.isLeaf) {
                        stack.push(curr.children[i]);
                    }
                    System.out.println(curr.keys[i].toString());
                }
                if (!curr.isLeaf) {
                    stack.push(curr.children[i]);
                }
            }
        }
    ```

What am I missing here?

标签: javaiterationbinary-treedepth-first-searchb-tree

解决方案


推荐阅读