/**
* node of Tree
* @author Prateek
*/
class Node {
public Node left;
public int data;
public Node right;
public Node(int val) {
this.data=val;
}
}
/**
* Calculate farthest left colummn and fatherst right column
* @author Prateek
*
*/
class VerticalColumns {
static int maxVal=0 ; // farthest right column
static int minVal=0; //farthest left column
/**
* Calculates farthest left colummn and fatherst right column
* @param root
* @param col
*/
public void totalCol(Node root , int col) {
if(root==null)
return ;
totalCol(root.left , col - 1 );
totalCol(root.right , col + 1 );
maxVal=min(col, maxVal);
minVal = max (col , minVal) ;
}
private int max(int val1, int val2) {
return val1 > val2 ? val1 : val2;
}
private int min(int val1, int val2) {
return val1 < val2 ? val1 : val2;
}
public static void main
(String[] args
) { Node root=new Node(12) ;
root.left =new Node(6);
root.left.right=new Node(8);
root.left.right.left=new Node(20);
root.left.right.left.left=new Node(24);
root.right=new Node(56);
root.right.left=new Node (70) ;
root.right.left.right=new Node(72);
root.right.left.right.right=new Node(34);
root.right.left.right.right.right=new Node(39);
VerticalColumns vObj=new VerticalColumns();
vObj.totalCol(root, 0);
System.
out.
println("Max: " + maxVal
); System.
out.
println("Min: " + minVal
); }
}
LyoqCiAqIG5vZGUgb2YgVHJlZQogKiBAYXV0aG9yIFByYXRlZWsKICovCmNsYXNzIE5vZGUgewoJcHVibGljIE5vZGUgbGVmdDsKCXB1YmxpYyBpbnQgZGF0YTsKCXB1YmxpYyBOb2RlIHJpZ2h0OwoKCXB1YmxpYyBOb2RlKGludCB2YWwpIAl7CgkJdGhpcy5kYXRhPXZhbDsKCX0KfQoKLyoqCiAqIENhbGN1bGF0ZSBmYXJ0aGVzdCBsZWZ0IGNvbHVtbW4gYW5kIGZhdGhlcnN0IHJpZ2h0IGNvbHVtbgogKiBAYXV0aG9yIFByYXRlZWsKICoKICovCiBjbGFzcyBWZXJ0aWNhbENvbHVtbnMgewoKCXN0YXRpYyBpbnQgbWF4VmFsPTAgOyAvLyBmYXJ0aGVzdCByaWdodCBjb2x1bW4KCXN0YXRpYyBpbnQgbWluVmFsPTA7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