forked from striver79/FreeKaTreeSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
L28_maximumWidthBtJava
34 lines (34 loc) · 1.04 KB
/
L28_maximumWidthBtJava
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
class Pair {
TreeNode node;
int num;
Pair(TreeNode _node, int _num) {
num = _num;
node = _node;
}
}
class Solution {
public int widthOfBinaryTree(TreeNode root) {
if(root == null) return 0;
int ans = 0;
Queue<Pair> q = new LinkedList<>();
q.offer(new Pair(root, 0));
while(!q.isEmpty()){
int size = q.size();
int mmin = q.peek().num; //to make the id starting from zero
int first = 0,last = 0;
for(int i=0; i<size; i++){
int cur_id = q.peek().num-mmin;
TreeNode node = q.peek().node;
q.poll();
if(i==0) first = cur_id;
if(i==size-1) last = cur_id;
if(node.left != null)
q.offer(new Pair(node.left, cur_id*2+1));
if(node.right != null)
q.offer(new Pair(node.right, cur_id*2+2));
}
ans = Math.max(ans, last-first+1);
}
return ans;
}
}