Your task is to implement the following function :
int height(TreeNode*)
Height of a binary tree is defined as the maximum number of edges encountered on any path from the root node till a leaf node.
You will be working with the following structure :
struct TreeNode {
int x;
struct TreeNode* L;
struct TreeNode* R;
}
You may only edit the BODY of the code, leaving the HEAD and the TAIL as it is.
Sample Input 0
7
4 2 1 3 6 7 5
Sample Output 0
2
Solution :
import java.util.*;
import java.io.*;
class Node{
Node left,right;
int data;
Node(int data){
this.data=data;
left=right=null;
}
}
class Solution{
public static int getHeight(Node root)
{
//Write your code here
if(root ==null)
return -1;
int left=getHeight(root.left);
int right=getHeight(root.right);
return Math.max(left, right) + 1;
}
public static Node insert(Node root,int data){
if(root==null){
return new Node(data);
}
else{
Node cur;
if(data<=root.data){
cur=insert(root.left,data);
root.left=cur;
}
else{
cur=insert(root.right,data);
root.right=cur;
}
return root;
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
Node root=null;
while(T-->0){
int data=sc.nextInt();
root=insert(root,data);
}
int height=getHeight(root);
System.out.println(height);
}
}