Java中有没有办法在满足某个条件时结束递归方法?
有没有办法在满足条件时突然返回到调用下面方法的方法?类似于循环的中断。
public void createTree(TreeNode tree) throws IOException {
if (i >= preorder.length) {
// Leave recursive method
} else if (preorder[i] == '0') {
tree.value = '0';
tree.left = tree.right = null;
i++;
} else {
tree.value = preorder[i];
i++;
tree.left = new TreeNode();
createTree(tree.left);
tree.right = new TreeNode();
createTree(tree.right);
}
}
谢谢。
Is there a way to abruptly return to the method that calls the method below when the condition is met? Something similar to a break for loops.
public void createTree(TreeNode tree) throws IOException {
if (i >= preorder.length) {
// Leave recursive method
} else if (preorder[i] == '0') {
tree.value = '0';
tree.left = tree.right = null;
i++;
} else {
tree.value = preorder[i];
i++;
tree.left = new TreeNode();
createTree(tree.left);
tree.right = new TreeNode();
createTree(tree.right);
}
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以简单地让该方法返回。然后递归将向后执行,并执行剩余的语句。
You can simply let the method return. Then the recursion will go backwards and the remaining statements will be executed.
您可以从该方法返回状态:
You could return a status from the method :
你可以抛出异常,但这似乎是“肮脏的”
you could throw an exception, but this seems to be "dirty"
您可能会考虑使用运行时异常,但我认为这不是一个好的设计。
如果我的递归走那么远,则意味着它是必需的......并且我可能会使用返回
You might consider using an runtimeexception but i do not think it is a good design.
If my recursion went that far it means that it was required... and i will probably used a return