如何遍历BTree而不以迭代方式递归?

问题描述

我需要B树LNR遍历(按顺序)。我找到了B树遍历here的算法。如何以迭代方式实现它而无需递归? 我找到了this question,但没有答案,问题中的代码是如此不清楚,似乎不正确。至少这不是LNR,也不适合我。 另外,我已经找到了很多简单的二叉树遍历示例,但我需要B树。

我使用Rust,但是很高兴看到任何语言或伪代码的答案。

解决方法

正如评论中已经提到的那样:如果您不希望使用递归(这将是一种方法),那么您将不得不使用堆栈来模仿它。

该堆栈上的条目将是一对,其中包括:

  • 对节点的引用,以及
  • 该节点内的当前索引(0 ... m -1),其中 m 是该节点上的分支数

作为示例,我将使用以下B树:

enter image description here

...并使用其JSON表示形式:

{
    "keys": [29],"children": [{
        "keys": [15,21],"children": [{
            "keys": [11,12]
        },{
            "keys": [18,20]
        },{
            "keys": [23,25,27]
        }]
    },{
        "keys": [35,42],"children": [{
            "keys": [31,33]
        },{
            "keys": [36,39]
        },{
            "keys": [45,47,50,55]
        }]
    }]
}

这是JavaScript中iterate函数的实现,该函数以LNR顺序返回键上的迭代器:

function * iterate(node) {
    let stack = []; // stack of [node,child-index] pairs
    
    stack.push([node,0]);
    while (stack.length > 0) {
        let [node,i] = stack.pop();
        if (!("children" in node)) { // bottom level has no "children" member
            for (let key of node.keys) {
                yield key;
            }
        } else if (i < node.children.length) {
            if (i > 0) {
                yield node.keys[i-1];
            }
            stack.push([node,i+1]);
            stack.push([node.children[i],0]);
        }
    }
}

// The example B-tree:
const btree = {"keys": [29],"children": [{"keys": [15,"children": [{"keys": [11,12]},{"keys": [18,20]},{"keys": [23,27]}]},{"keys": [35,"children": [{"keys": [31,33]},{"keys": [36,39]},{"keys": [45,55]}]}]};

// Consume the iterator and output
console.log(...iterate(btree));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...