-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJuly9_2020.java
39 lines (35 loc) · 1.08 KB
/
July9_2020.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Max width of binary tree - level order traversal woth hack
class Solution {
public int widthOfBinaryTree(TreeNode root)
{
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
int max = 1, leftmost = 1, rightmost = 1;
root.val = 1;
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if (i == 0) {
leftmost = cur.val;
}
if (i == size - 1) {
rightmost = cur.val;
}
if (cur.left != null) {
cur.left.val = cur.val * 2;
queue.offer(cur.left);
}
if (cur.right != null) {
cur.right.val = cur.val * 2 + 1;
queue.offer(cur.right);
}
}
max = Math.max(max, rightmost - leftmost + 1);
}
return max;
}
}