fork download
  1. /**
  2.  * node of Tree
  3.  * @author Prateek
  4.  */
  5. class Node {
  6. public Node left;
  7. public int data;
  8. public Node right;
  9.  
  10. public Node(int val) {
  11. this.data=val;
  12. }
  13. }
  14.  
  15. /**
  16.  * Calculate farthest left colummn and fatherst right column
  17.  * @author Prateek
  18.  *
  19.  */
  20. class VerticalColumns {
  21.  
  22. static int maxVal=0 ; // farthest right column
  23. static int minVal=0; //farthest left column
  24. /**
  25. * Calculates farthest left colummn and fatherst right column
  26. * @param root
  27. * @param col
  28. */
  29. public void totalCol(Node root , int col) {
  30.  
  31. if(root==null)
  32. return ;
  33.  
  34. totalCol(root.left , col - 1 );
  35. totalCol(root.right , col + 1 );
  36.  
  37. maxVal=min(col, maxVal);
  38. minVal = max (col , minVal) ;
  39. }
  40.  
  41. private int max(int val1, int val2) {
  42. return val1 > val2 ? val1 : val2;
  43. }
  44.  
  45. private int min(int val1, int val2) {
  46. return val1 < val2 ? val1 : val2;
  47. }
  48.  
  49. public static void main(String[] args) {
  50. Node root=new Node(12) ;
  51. root.left =new Node(6);
  52. root.left.right=new Node(8);
  53. root.left.right.left=new Node(20);
  54. root.left.right.left.left=new Node(24);
  55.  
  56. root.right=new Node(56);
  57. root.right.left=new Node (70) ;
  58.  
  59. root.right.left.right=new Node(72);
  60. root.right.left.right.right=new Node(34);
  61. root.right.left.right.right.right=new Node(39);
  62.  
  63.  
  64. VerticalColumns vObj=new VerticalColumns();
  65. vObj.totalCol(root, 0);
  66.  
  67. System.out.println("Max: " + maxVal);
  68. System.out.println("Min: " + minVal);
  69. }
  70. }
  71.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Max: -2
Min: 3