Full width home advertisement

Latest Phones

Phone Applications

Post Page Advertisement [Top]

How to find height of binary tree

Max height is computed by taking the longest height of any sub tree starting from root node. The logic is to iterate through either left sub tree or right subtree and consider the longer height and further iterate to that sub tree till we reach the leaf. This way we can obtain the maximum depth/height of a binary tree.

The height of a binary tree is found using the recursive Depth-First Search (DFS) algorithm, as shown below:
  1. Base case: If there is no node, return 0.
  2. Else: If there are 1 or 2 children, return the maximum of the height of the left and right sub-trees, plus 1 to account for the current node. The height of a sub-tree is found by recursively calling the function, and passing the child node as the parameter.

int max_height(struct node* node)
{
  int l_depth;
  int r_depth;
  if (node==NULL) { 
    return(0); 
  } else { 
    /* compute the height of each sub tree */
    l_depth = max_height (node->left); 
    r_depth = max_height (node->right); 
    /* use the longer one */
    if (l_depth > r_depth) {
      return (l_depth + 1);
    } else {
      return (r_depth + 1);
    }
  }
}

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Aahit Chandra