Compute height of a tree at root
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (2805)

Write a function to compute the height of a binary tree at the root.


Posted Answers

 
public int computeHeight(Node node){

/* If the tree is empty */
if(node == null)
return -1;

/* Compute the depth of subtrees recursively */
int heightLeft = computeHeight(node.left);
int heightRight = computeHeight(node.right);

/* Compare the height in the left and right subtree : return the maximum one*/
if(heightLeft > heightRight)
return heightLeft + 1;
else
return heightRight + 1;
}


Time complexity = \( O(n) \) where \( n \) is the number of nodes in the binary tree.

You need to Sign In to post your solution.