所以我正在尝试编写一个前序遍历方法。我正在使用自己的具有多个子节点的节点。为了跟踪它们,每个节点都有一个子节点数组。当尝试递归遍历节点映射时,我遇到了 IndexOutOfBoundsException,它会终止程序,而不是仅仅检查它,因为空值可以继续。我已尽力使用 try block 捕获它,但按照我现在将其组合在一起的方式,该方法仅遍历每个子数组中的第一个子数组。
这是我的代码:
private void traverse (Node root) {
peggyPoints.add(root);
int i = 0;
if (root.nexts != null) {
try {
Node current = root.nexts.get(i);
while (current != null) {
traverse(current);
current = current.nexts.get(i+1);
}
} catch (IndexOutOfBoundsException e) { }
}
}
peggyPoints 是一个数组列表,用于跟踪访问的节点。 nexts 是给定节点的子节点数组。
给定一张 map
1
/ \
2 3
/ \ \
4 5 6
访问的节点应该是 1, 2, 4, 5, 3, 6,但根据我的数据,它只访问 1, 2, 4。
提前致谢!
最佳答案
我认为您应该采取的方法是为当前节点添加一个 Hook ,然后递归地左右遍历两者。逻辑上错误的代码行是:
current = current.nexts.get(i+1);
我认为你应该再次使用root
来获取下一个节点进行遍历,即
current = root.nexts.get(i+1);
但是,您甚至可以不这样做,只需在 nexts
列表中使用 for in 循环,并完全取消管理循环索引:
private void traverse (Node root) {
peggyPoints.add(root);
if (root.nexts != null) {
for (Node current : root.nexts) {
traverse(current);
}
}
}
关于java - 带有 IndexOutOfBoundsException 的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887742/