/* package whatever; // don't place package name! */
/**
* Node of a Binary Tree
* @author Prateek
*
*/
class Node {
public Node left;
public int data;
public Node right;
public Node(int val) {
this.data=val;
}
}
/**
* Find diameter of Binary Tree
* @author Prateek
*
*/
class Diameter {
/**
* Subroutine to calculate diameter
* @param root
* @return diameter
*/
public int diameter(Node root){
if(root==null)
return 0;
int lHeight=height(root.left);
int rHeight=height(root.right);
int ldiameter=diameter(root.left);
int rdiameter=diameter(root.right);
return max(lHeight + rHeight + 1 , max(ldiameter, rdiameter)) ;
}
/**
* @param root of the tree
* @return height of the tree
*/
public int height(Node root) {
if(root == null)
return 0;
int lHeight=height(root.left);
int rHeight=height(root.right);
return max(lHeight,rHeight) + 1;
}
/**
* @return maximum val
*/
private int max(int val1, int val2) {
return val1 > val2 ? val1 : val2;
}
public static void main
(String[] args
) { Node root=new Node(52);
root.left=new Node(30);
root.right=new Node(76);
root.left.left=new Node(22);
root.left.right=new Node(82);
root.right.left=new Node(54);
root.right.right=new Node(12);
Diameter obj=new Diameter();
System.
out.
println(obj.
diameter(root
)); }
}