【发布时间】:2022-01-30 11:03:40
【问题描述】:
我的任务是搜索并找到二叉搜索树的高度。为了解决这个问题,我想出了以下解决方案。
static int countL = 0 ;
static int countR = 0 ;
public static int getHeight(Node root) {
if (root.left != null) {
countL++;
getHeight(root.left);
}
if (root.right != null) {
countR++;
getHeight(root.right);
}
count = Math.max(countL, countR);
return count;
}
不是最优雅的,但它解决了某些树的问题。在网上搜索我找到了另一种解决方案。除了更优雅的代码之外,我上面的代码和下面的代码有什么区别?为了成为更精通的编码人员,减少代码行数的最佳方法是什么。我的任务是了解我哪里出错了,以及下面的代码与我的相比有什么不同
private static int getHeight(Node root){
int heightLeft = 0;
int heightRight = 0;
if (root.left != null) {
heightLeft = getHeight(root.left) + 1;
}
if (root.right != null) {
heightRight = getHeight(root.right) + 1;
}
return (heightLeft > heightRight ? heightLeft : heightRight);
}
【问题讨论】:
标签: java recursion binary-search-tree