Height of a tree with only one node

后端 未结 6 1368
天涯浪人
天涯浪人 2020-12-14 01:29

According to Wikipedia,

The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one

6条回答
  •  离开以前
    2020-12-14 02:28

    Assuming you are calculating the height in a recursive manner in the node class I would do this to return the height without including height of the root (java code):

    int height(){
        int leftHeight = 0;
        int rightHeight = 0;
        if(left != null)
            leftHeight =+ left.height() + 1;
        if(right != null)
            rightHeight =+ right.height() + 1;
        return Math.max(leftHeight, rightHeight);
    }
    

    if you want to include the height of the root, then I would do this:

    int height(){
        int leftHeight = 0;
        int rightHeight = 0;
        if(left != null)
            leftHeight =+ left.height();
        if(right != null)
            rightHeight =+ right.height();
        return Math.max(leftHeight, rightHeight) + 1;
    }
    

提交回复
热议问题