我使用下面给出的方法来计算二叉树的高度,

int height(Node root)
{
    if (root == null)
       return 0;
    else
    {
        int lheight = height(root.left);
        int rheight = height(root.right);

        if (lheight > rheight)
            return(lheight+1);
        else return(rheight+1);
    }
}


这将返回lheight =2。最初,我认为每次对height(root.left)进行递归调用时,lheight都会增加1。但是后来我添加了printf语句并再次运行它,

int height(Node root)
{
    if (root == null)
       return 0;
    else
    {
        int lheight = height(root.left);
        System.out.print(lheight);
        int rheight = height(root.right);

        if (lheight > rheight)
            return(lheight+1);
        else return(rheight+1);
    }
}


printf语句打印此0 1 0 20。每个递归调用的lheight值如何变化?我不是在寻找新的解决方案。我知道这可以通过很多方式来完成。我只想了解此代码段中的情况。这是二叉树图像链接。
Binary tree

最佳答案

做这样的事情-

int height(Node root)
{
    if (root == null)
       return 0;
    else
    {
        return 1+ Math.max(height(root.left),height(root.right));
    }
}


像这样计算身高

int height = height(root); //this is the height not inside the function


我还没有编译它-但这是获取树的高度的方法(c / c ++ / java / ..)

09-30 17:21
查看更多