java - 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?
解决方案
推荐阅读
- javascript - 使用两个参数对 users.findOne 进行续集
- python - 有没有更好的方法在 python 中编写这个代码段?
- python-3.x - 如何正确继承类方法
- package - atom包安装程序出错,显示搜索失败
- java - 字符串和枚举类型变量的复合主键
- javascript - 如何在 React 函数 Return() 中设置 if-else 语句?
- sql - 如何从 IF ELSE 存储过程中的表中选择多个列
- kubernetes - 我想用用户名和密码在 Kubernetes 中创建一个用户。我尝试使用谷歌搜索,但只能找到使用证书密钥创建用户
- javascript - Vue 在与窗口宽度相关的条件下表现得很奇怪
- azure - 使用 Azure FrontDoor 按比例平衡 2 个 API 终结点