Thursday, January 14, 2016

Tree: Height of a binary tree - Hacker Rank Solution

The height of a binary tree is the number of nodes on the largest path from root to any leaf. You are given a pointer to the root of a binary tree. Return the height of the tree.

You only have to complete the function.
Input Format
You are given a function,
int height_of_bt(node * root)
{

}
Output Format
Return a single value equal to the height of the binary tree.
Sample Input
     3
   /   \
  5     2
 / \    /
1   4  6
      /
     7
Sample Output
4
Explanation
The maximum length root to leaf path is 3->2->6->7. There are 4 nodes in this path. Therefore the height of the binary tree = 4.
--------------------------------------------------------------------------------------------------------------

/*The tree node has data, left child and right child
struct node
{
    int data;
    node* left;
    node* right;
};

*/
int c=1;
int height(node * root)
{
  if(root == NULL)
       return 0;

   /* If tree is not empty then height = 1 + max of left
      height and right heights */  
   return 1 + max(height(root->left), height(root->right));
}
-------------------------------------------------------------------------------------------------------------
Powered by Blogger.