13

I need help with the theory on calculating the height of a binary tree, typically the notation.

I have read the following article:

Calculating height of a binary tree

And one of the posts gives the following notation:

height(node) = max(height(node.L), height(node.R)) + 1

Let's assume I have the following binary tree:

     10
   /   \  
  5    30
 / \   /  \ 
4  8  28  42

Do I therefore calculate the max value on the left node (8) and the max node on the right (42) and then add 1? I don't quite understand how this notation works in order to calculate the height of the tree.

Community
  • 1
  • 1
Phorce
  • 2,422
  • 11
  • 34
  • 73
  • It's a recursive algorithm. `height` calls itself until it gets to the bottom of each branch of the tree. – Robert Harvey May 21 '13 at 18:53
  • I would add that, when it gets to the bottom, it checks to see if the height is greater than the existing stored height, and, if so, updates it. – Chris Chambers May 21 '13 at 18:54
  • @ChrisChambers Thanks for the reply. So are we multiplying the `node.L` by the `node.R` What would be the height of the current tree given, as an example? – Phorce May 21 '13 at 18:56
  • @Phorce : We are not multiplying anything. node.L refers to the left child of the node. The height of the current tree would be 2 – cvraman May 21 '13 at 18:57
  • 1
    I would recommend that the tree height be set as a property of your tree class whenever you insert into it. That is, each time you insert, check and see if you went farther down the tree, and, if so, update the height. – Chris Chambers May 21 '13 at 18:58
  • @Phorce: Each child of the root of the tree, is also a tree rooted at said child node. Each of their children, is a tree as well. *Every node in the tree* is itself a tree. To find the height of the tree, you just find the height of each of the child trees, take the biggest of those numbers, and add 1 to count yourself. – cHao May 21 '13 at 21:02

9 Answers9

23

I'll try to explain how this recursive algorithm works:

height(10) = max(height(5), height(30)) + 1

height(30) = max(height(28), height(42)) + 1
height(42) = 0 (no children)
height(28) = 0 (no children)

height(5) =  max(height(4), height(8)) + 1
height(4) = 0 (no children)
height(8) = 0 (no children)

So if you want to calculate height(10), you have to expand the recursion down, and than substitute results backwards.

height(5)  = max(0, 0) + 1
height(30) = max(0, 0) + 1
height(10) = max(1, 1) + 1
height(10) = 2

EDIT:

As noted in comments:
height of binary tree = number of layers - 1
Therefore there should be assumption that height of empty node is equal to -1 i.e:

height(empty) = -1 

or

height(null) = -1 

this way

height(42) = max(height(null), height(null)) + 1
height(42) = max(-1, -1) + 1
height(42) = -1 + 1
height(42) = 0

I have corrected calculation above.

Ondrej Bozek
  • 9,501
  • 6
  • 48
  • 66
  • This question has helped a lot with my lab homework...What is the purpose of calculating the max of the left and right heights? – Riptyde4 Nov 11 '13 at 18:23
  • @Riptyde4 The tree you see above has the same height, either go left or right. But think of the case where for example. In the original example attach a number 6 below number 28. That's why we have to get the max. – jasxir Oct 24 '15 at 12:07
  • 1
    This answer is a good explanation of recursion, but it incorrectly calculates the height of a binary tree. The end of recursion (when input node = `NULL`) should return `-1` not `0`. I've provided the correct answer [below](https://stackoverflow.com/a/45293377/5567854). For reference, this is a repeated question, and the other stack overflow question also has the correct answer, [here](https://stackoverflow.com/a/2597754/5567854) – David John Coleman II Jul 25 '17 at 03:36
22

Height of the tree is the length of the path from the root to the deepest node in the tree. Here is the shortest algo to do so

int height(Node root){
   if(root == null )
       return 0;
   return 1+max{height(root.left), height(root.right)};
}
roger_that
  • 8,273
  • 15
  • 56
  • 94
  • @kimbaudi There is a base condition to check if any of the sub child is present or not. I believe this will work for all binary trees. Still, I would love to have a counter test case if any. – roger_that Mar 01 '17 at 06:44
  • Sorry @roger_that. Your algorithm handles the case where either one of the child nodes in a binary tree is null. However, the height calculation doesn't seem correct. Looking at OP binary tree, the height of it is 2. But your algorithm calculates it as 3. I'm sure the height at root node is 0 (not 1). – kimbaudi Mar 01 '17 at 23:00
  • @kimbaudi: By definition, "HEIGHT is defined as the number of nodes in the longest path from the root node to a leaf node". So you see. – roger_that Mar 02 '17 at 07:26
  • 1
    I disagree. The HEIGHT its the number of nodes from the root node to the leaf node EXCEPT the root node itself. Even the wikipedia example of binary tree: https://en.wikipedia.org/wiki/Binary_tree doesn't calculate the height that way. – kimbaudi Mar 02 '17 at 17:51
  • Minor fix in above algorithm, return -1 in case root is null. int height(Node root){ if(root == null ) return -1; return 1+max{height(root.left), height(root.right)}; } – AiOsN Apr 01 '19 at 10:33
2

Do u know the definition of node's height? I would answer it as the farthest distance to a reachable leaf(so all leaf have height 0)...now try to find the height of every node from bottom to top..that would your algo..

sethi
  • 1,749
  • 1
  • 16
  • 27
2

Find out the root node, then look for the longest path that u can cover(means the maximum number of node you can cover in that path), if u get that path, then check how many branches or edges you have covered, the total number of branches you have covered is the height of the tree

Dip686
  • 501
  • 3
  • 14
1

Repeated Question

Despite being good introductions to recursion, I'm a bit surprised by all the incorrect answers as to the height of a binary tree, so I thought I'd offer the correct solution. I did some digging and this question is answered properly here: https://stackoverflow.com/a/2597754/5567854.

Reference

According to Wikipedia, "A tree consisting of only a root node has a height of 0", not 1 as the other answers state. Therefore, with the example from the question:

     10
   /   \  
  5    30
 / \   /  \ 
4  8  28  42

If 10 was the root node to find the height of that tree, then the height is 2, not 3.

Correct Code

This solution is one of many possible solutions in C Language...

size_t binary_tree_height(const binary_tree_t *tree)
{
    size_t r, l, height = 0;

    if (tree)
    {
        r = tree->right ? binary_tree_height(tree->right) + 1 : 0;
        l = tree->left ? binary_tree_height(tree->left) + 1 : 0;
        height += (r > l ? r : l);
    }
    return (height);
}
0

The highest number of nodes that is possible in a way starting from the first node (ROOT) to a leaf node is called the height of tree. The formula for finding the height of a tree h=i(max)+1 , where h is the height and I is the max level of the tree

safi
  • 9
  • 1
0
#include<stdio.h>
#include<stdlib.h>


/* A binary tree node has data, pointer to left child 
   and a pointer to right child */
struct node 
{
    int data;
    struct node* left;
    struct node* right;
};

/* Compute the "maxDepth" of a tree -- the number of 
    nodes along the longest path from the root node 
    down to the farthest leaf node.*/
int maxDepth(struct node* node) 
{
   if (node==NULL) 
       return 0;
   else
   {
       /* compute the depth of each subtree */
       int lDepth = maxDepth(node->left);
       int rDepth = maxDepth(node->right);

       /* use the larger one */
       if (lDepth > rDepth) 
           return(lDepth+1);
       else return(rDepth+1);
   }
} 

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data) 
{
    struct node* node = (struct node*)
                                malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return(node);
}

int main()
{
    struct node *root = newNode(1);

    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5); 

    printf("Hight of tree is %d", maxDepth(root));

    getchar();
    return 0;
}
sankar
  • 1
  • 1
0

You can use the recursive approach.

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

-1

C enthousiasts, feel free to have a read at this article:

http://www.csegeek.com/csegeek/view/tutorials/algorithms/trees/tree_part3.php

I re-aranged the C code to PHP:

function getTreeHeight($node) {
    if (!isset($node['left']) && !isset($node['right'])) {
        return 0;
    }

    $leftHeight  = getTreeHeight($node['left']);
    $rightHeight = getTreeHeight($node['right']);

    if ($leftHeight > $rightHeight) {
        return $leftHeight + 1;
    } else {
        return $rightHeight + 1;
    }
}

$array = array(
    'value' => 5,
    'left' => array(
        'value' => 2,
        'left' => array(
            'value' => 1,
        ),
        'right' => array(
            'value' => 4
        ),
    ),
    'right' => array(
        'value' => 11,
        'left' => array(
            'value' => 7
        ),
        'right' => array(
            'value' => 23,
            'left' => array(
                'value' => 16
            ),
            'right' => array(
                'value' => 34
            ),
        ),
    )
);

echo getTreeHeight($array); //output 3
Julian
  • 3,177
  • 2
  • 29
  • 43