Java:For 循环在递归函数中的一个元素后停止
我正在从头开始用java构建一个树结构。为了获取树的高度,我使用递归函数。
每个注释 (IP) 包含其拥有的所有连接的列表,包括父级。我的想法是循环所有子项,并在不是父项时再次调用 height 函数。
我的问题是,它只调用一个孩子,并且不会循环所有可能的孩子。也许有人可以告诉我我的错在哪里。
如果一个 Note 有两个孩子,并且每个孩子还有另外两个。它在两次迭代中仅查看第一个。
public int recursiveGetHight(final Node node, Node parent) {
Node viewPoint = getViewPoint(node);
int h = 0;
for (Node child : viewPoint.getChildren()) {
if (child.getChildren().size() <= 1) {
return 0;
} else if(parent == null || child.getValue() != parent.getValue()){
h = recursiveGetHight(child, viewPoint) + 1;
return h;
}
}
return h;
}
例如:
root
- note 1
- sub note 1
- sub note 2
- x
- y
- note 2
- sub note 1
- z
- sub note 2
int h = recurisvHeight(root, null)
result should be 3 but the function returns 2.
如果我在 for 循环内使用 print 命令,
System.out.println(child);
它会显示: 注1 分注 1
I am building a tree structure in java from scratch. For getting the height of my tree I am using a recursive function.
Each note (IP) contains a list of all connections it has, including there parent. My idea was to loop over all children and call the height function again when it's not the parent.
My problem is, that it only calls one child and does not loop over all possible children. Maybe someone can tell me where is my fault.
If one Note has two children and each of them also has another two. It only views the first one at both iterations.
public int recursiveGetHight(final Node node, Node parent) {
Node viewPoint = getViewPoint(node);
int h = 0;
for (Node child : viewPoint.getChildren()) {
if (child.getChildren().size() <= 1) {
return 0;
} else if(parent == null || child.getValue() != parent.getValue()){
h = recursiveGetHight(child, viewPoint) + 1;
return h;
}
}
return h;
}
Exempel:
root
- note 1
- sub note 1
- sub note 2
- x
- y
- note 2
- sub note 1
- z
- sub note 2
int h = recurisvHeight(root, null)
result should be 3 but the function returns 2.
If I at a print command inside the for loop
System.out.println(child);
it shows:
note1
sub note 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为你使用了 return,当你返回时你的函数就结束了。
您必须删除第一个 return = 0 并创建一个 child 的 ArrayList,并通过将 child 追加到列表中来替换 by 循环中的 return h 。
It's because you use return, when you make a return your function end.
You have to remove the first return = 0 and make an ArrayList of child and replace return h in the by loop by append the child in the list.