fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. /**
  4.  * Node of a Binary Tree
  5.  * @author Prateek
  6.  *
  7.  */
  8. class Node {
  9. public Node left;
  10. public int data;
  11. public Node right;
  12.  
  13. public Node(int val) {
  14. this.data=val;
  15. }
  16. }
  17.  
  18. /**
  19.  * Find diameter of Binary Tree
  20.  * @author Prateek
  21.  *
  22.  */
  23. class Diameter {
  24.  
  25. /**
  26. * Subroutine to calculate diameter
  27. * @param root
  28. * @return diameter
  29. */
  30. public int diameter(Node root){
  31. if(root==null)
  32. return 0;
  33.  
  34. int lHeight=height(root.left);
  35. int rHeight=height(root.right);
  36.  
  37. int ldiameter=diameter(root.left);
  38. int rdiameter=diameter(root.right);
  39.  
  40. return max(lHeight + rHeight + 1 , max(ldiameter, rdiameter)) ;
  41. }
  42.  
  43. /**
  44. * @param root of the tree
  45. * @return height of the tree
  46. */
  47. public int height(Node root) {
  48. if(root == null)
  49. return 0;
  50.  
  51. int lHeight=height(root.left);
  52. int rHeight=height(root.right);
  53.  
  54. return max(lHeight,rHeight) + 1;
  55. }
  56.  
  57. /**
  58. * @return maximum val
  59. */
  60. private int max(int val1, int val2) {
  61. return val1 > val2 ? val1 : val2;
  62. }
  63.  
  64. public static void main(String[] args) {
  65. Node root=new Node(52);
  66.  
  67. root.left=new Node(30);
  68. root.right=new Node(76);
  69. root.left.left=new Node(22);
  70. root.left.right=new Node(82);
  71. root.right.left=new Node(54);
  72. root.right.right=new Node(12);
  73.  
  74.  
  75. Diameter obj=new Diameter();
  76. System.out.println(obj.diameter(root));
  77. }
  78. }
Success #stdin #stdout 0.06s 380160KB
stdin
Standard input is empty
stdout
5