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));
}
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