Java 递归过程如何计算BST的高度?

Java 递归过程如何计算BST的高度?,java,recursion,data-structures,binary-search-tree,Java,Recursion,Data Structures,Binary Search Tree,我有一个二叉树,高度是根据以下代码计算的- public int height(Node root) { if (root == null) return -1; Node focusNode = root; int leftHeight = focusNode.leftChild != null ? height( focusNode.leftChild) : 0; int rightHeight = focusNode.rightChil

我有一个二叉树,高度是根据以下代码计算的-

public int height(Node root) {

    if (root == null)
        return -1;

    Node focusNode = root; 
    int leftHeight = focusNode.leftChild != null ? height( focusNode.leftChild) : 0;
    int rightHeight = focusNode.rightChild != null ? height( focusNode.rightChild) : 0;
    return 1 + Math.max(leftHeight, rightHeight);

}
如果根的左或右子级不为null,它将再次调用相同的height方法并继续递归。否则,它返回零。对我来说,很难理解如何计算增加值(比如说,像c+=1,你看到它为每个循环加1)


有人能向我详细解释一下吗

此处的计数增加:

return 1 + Math.max(leftHeight, rightHeight);

因为每个递归调用返回最后两个递归调用结果中较高的一个。

让我们使用一个简单的示例树:

  r
 / 
A   
为了确定它的高度,我们从
r
开始。为了计算
r
下面子树的高度,我们首先计算左子树的高度,然后计算右子树的高度。然后我们选择较高的子树并将
1
添加到其高度(即,我们将
r
(1)的高度添加到较高的子树)

现在,左子树的高度是以
A
为根的树的高度(忽略此时存在的
r
)。递归表示,以
A
为根的树的高度再次是其最高子树加上
1
的高度。
A
的左子树为
NULL
,因此其高度为
0
A
的右子树也是
NULL
,因此其高度也是
0

因此,以
A
为根的子树的高度具有高度
max(0,0)+1
,这也是我们返回到
r
的数字:
r
的左子树的高度为
1

int rightHeight = focusNode.rightChild != null ? height( focusNode.rightChild) : 0;
// if the right subtree exists, calculate its height.
// the height is zero if there is no right subtree
现在我们向右转
r
的右子树为
NULL
,因此其高度为
0

所以
r
有一个高度
1的子树(左)和一个高度
0的子树(右)。我们选择较高子树的高度并添加
1

return 1 + Math.max(leftHeight, rightHeight);
// pick higher subtree and add 1 to its height
// to include the root node.
因此,以
r
为根的树的高度为
2


注意,这里没有涉及循环,只有递归。通过先解决每个(较小)子树的问题,然后结合结果来解决问题。

非常感谢您的回答感谢您花时间写详细内容。我真的很感激。
return 1 + Math.max(leftHeight, rightHeight);
// pick higher subtree and add 1 to its height
// to include the root node.