Given a binary tree, write a function to get the maximum width of the given tree. Width of a tree is maximum of widths of all levels.
Let us consider the below example tree.
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
For the above tree,
width of level 1 is 1,
width of level 2 is 2,
width of level 3 is 3
width of level 4 is 2.
So the maximum width of the tree is 3.
class Solution {
// Using levelOrder traversal
private static int solveLevelWay(Node root) {
if (root == null)
return 0;
Queue<Node> q = new LinkedList<>();
q.add(root);
int maxCount = Integer.MIN_VALUE;
int count = 1;
while (q.size() != 0) {
int newCount = 0;
int count = q.size();
while (count-- > 0) {
Node temp = q.poll();
if (temp.left != null) {
q.add(temp.left);
newCount++;
}
if (temp.right != null) {
q.add(temp.right);
newCount++;
}
}
maxCount = Math.max(maxCount, newCount);
}
return maxCount;
}
}