forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0662-maximum-width-of-binary-tree.java
More file actions
36 lines (33 loc) · 977 Bytes
/
0662-maximum-width-of-binary-tree.java
File metadata and controls
36 lines (33 loc) · 977 Bytes
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
class Solution {
public int widthOfBinaryTree(TreeNode root) {
int res = 0;
Queue<tuple> q = new LinkedList<>();
q.add(new tuple(root, 1, 0));
int prevLevel = 0, prevNum = 1;
while(!q.isEmpty()){
tuple curr = q.poll();
TreeNode node = curr.node;
int num = curr.num, level = curr.level;
if(level > prevLevel){
prevLevel = level;
prevNum = num;
}
res = Math.max(res, num - prevNum + 1);
if(node.left != null)
q.add(new tuple(node.left, num*2, level + 1));
if(node.right != null)
q.add(new tuple(node.right, num*2 + 1, level + 1));
}
return res;
}
}
class tuple{
TreeNode node;
int num;
int level;
public tuple(TreeNode node, int num, int level){
this.node = node;
this.num = num;
this.level = level;
}
}