我的递归条件是否适合计算二叉树高度? [英] Are my recursion conditions right to compute binary tree height?
本文介绍了我的递归条件是否适合计算二叉树高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在你的帮助下知道我的代码是对还是错,因为遗憾的是我无法运行它来检查。
I'm trying to know whether my code is right or wrong with your help, because sadly I can't run it to check.
没有编译错误。我要做的是找到二叉树的高度。当然,树不必平衡。
There are no compile errors. What I'm trying to do is to find the height of a binary tree. The tree does not have to be balanced, of course.
public int height(RBNode t) {
if (t == null)
return 0;
int heightLeft = height(t.left);
int heightRight = height(t.right);
if (heightLeft > heightRight) {
return heightLeft + 1;
} else {
return (heightRight + 1);
}
}
您认为递归条件是否合适?我的朋友声称它总会返回0。
Do you think the recursion conditions are right? My friend claims that it will always return 0.
推荐答案
非常紧凑的版本:
public int height(RBNode t) {
if (t == null) {
return 0;
}
return Math.max(height(t.left), height(t.right)) + 1;
}
这篇关于我的递归条件是否适合计算二叉树高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文