/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class Node {
TreeNode cur;
int curCol;
public Node (TreeNode cur, int curCol) {
this.cur = cur;
this.curCol = curCol;
}
}
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int res = 1;
Queue<Node> q = new LinkedList<>();
q.offer(new Node(root, 0));
while (!q.isEmpty()) {
int curSize = q.size();
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int i = 0; i < curSize; i++) {
Node curNode = q.poll();
TreeNode cur = curNode.cur;
int curCol = curNode.curCol;
min = Math.min(min, curCol);
max = Math.max(max, curCol);
if (cur.left != null) {
q.offer(new Node(cur.left, curCol * 2 + 1));
}
if (cur.right != null) {
q.offer(new Node(cur.right, curCol * 2 + 2));
}
}
res = Math.max(res, max - min + 1);
}
return res;
}
}