我试图在你的帮助下知道我的代码是对还是错,因为遗憾的是我无法检查它.
没有编译错误.我想要做的是找到二叉树的高度.当然,树不必平衡.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
你认为递归条件是对的吗?我的朋友声称它总会返回0.
看起来很好,虽然我个人改变了最后一点:
return Math.max(heightLeft, heightRight) + 1;
Run Code Online (Sandbox Code Playgroud)
我担心你根本无法运行它...为什么你不能围绕这个编写单元测试?我对任何无法测试的代码感到紧张:)
真正的紧凑版本:
public int height(RBNode t) {
if (t == null) {
return 0;
}
return Math.max(height(t.left), height(t.right)) + 1;
}
Run Code Online (Sandbox Code Playgroud)