Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, March 27, 2017

Find Height of Tree


/*
    class Node
    int data;
    Node left;
    Node right;
*/
static int height(Node root) {
      if(!(root instanceof Node))
          {
          return -1;
      }
        return 1+Math.max(height(root.left),height(root.right));
    }


Explanation :

Check while root is not null i,e. if it is not instance of node class

return -1 if it is leaf node 

At the end find max of two nodes and add 1 as we passed -1 before

0 Comments:

Post a Comment

Stats