我在Java中写了一种递归方法来计算树的高度,我的问题是如何获得这种方法以一次打印高度
因此,这是我的方法:
public int getHeight(IntTreeNode root) {
if(root == null) {
return 0;
}
int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
System.out.println(height);
}
return height;
}
我知道,由于这是一种递归方法,它将打印循环的高度,直到达到最终高度,但是我想要的是这种方法仅打印最终高度。关于如何使这项工作的任何想法?谢谢。
So here is my method:
public int getHeight(IntTreeNode root) {
if(root == null) {
return 0;
}
int height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
System.out.println(height);
}
return height;
}
I know that since it's a recursive method it will print the height in loops until it reaches the final height, but what I want is for this method to print the final height only. Any ideas on how to make this work anyone? thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用第二种方法(例如
printheight
)打印高度,并使用getheight
方法仅返回高度。E. G。:
You should use a second method e. g.
printHeight
to print the height and use thegetHeight
method only to return the height.E. g.: