class Node {
public Node left;
public int data;
public Node right;
public Node(int val) {
this.data=val;
}
}
/**
* Calulate Max Width of a Binary Tree
* @author Prateek
*
*/
class MaxWidth {
/** Calculates width for all levels of the tree
* @param root
* @return max width of Binary Tree
*/
public int maxWidth(Node root) {
int level=2;
int curLevel=1; // root is at level 1
int maxLevel=0; // if root is null max level is 0
while(curLevel > 0) // for a null node current level will be 0, terminating condition
{
curLevel = width(root, level++);
maxLevel=max(curLevel, maxLevel) ;
}
return maxLevel;
}
/**
* @return Number of nodes at a given level
*/
private int width(Node root , int level ) {
if(root == null)
return 0;
if(level==1)
return 1;
return width(root.left , level-1) + width(root.right , level-1) ;
}
private int max(int curLevel, int maxLevel) {
return curLevel > maxLevel ? curLevel : maxLevel ;
}
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);
MaxWidth obj=new MaxWidth();
System.
out.
println(obj.
maxWidth(root
)); }
}
Y2xhc3MgTm9kZSB7CglwdWJsaWMgTm9kZSBsZWZ0OwoJcHVibGljIGludCBkYXRhOwoJcHVibGljIE5vZGUgcmlnaHQ7CgoJcHVibGljIE5vZGUoaW50IHZhbCkgCXsKCQl0aGlzLmRhdGE9dmFsOwoJfQp9CgovKioKICogQ2FsdWxhdGUgTWF4IFdpZHRoIG9mIGEgQmluYXJ5IFRyZWUKICogQGF1dGhvciBQcmF0ZWVrCiAqCiAqLwpjbGFzcyBNYXhXaWR0aCB7CgoJLyoqIENhbGN1bGF0ZXMgd2lkdGggZm9yIGFsbCBsZXZlbHMgb2YgdGhlIHRyZWUKCSAqIEBwYXJhbSByb290CgkgKiBAcmV0dXJuIG1heCB3aWR0aCBvZiBCaW5hcnkgVHJlZQoJICovCglwdWJsaWMgaW50IG1heFdpZHRoKE5vZGUgcm9vdCkgewoKCQlpbnQgbGV2ZWw9MjsgIAoJCWludCBjdXJMZXZlbD0xOyAgIC8vIHJ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