Skip to content

Commit 5e77ff2

Browse files
Create 662-Maximum-Width-of-Binary-Tree.java
1 parent e8fbafd commit 5e77ff2

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//This solution helped https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/106645/C%2B%2BJava-*-BFSDFS3liner-Clean-Code-With-Explanation
2+
//This video helped https://www.youtube.com/watch?v=ZbybYvcVLks&ab_channel=takeUforward
3+
4+
class Solution {
5+
public int widthOfBinaryTree(TreeNode root) {
6+
Queue<Pair<TreeNode, Integer>> q = new LinkedList<>();
7+
int maxWidth = 0;
8+
q.offer(new Pair(root, 1));
9+
while (!q.isEmpty()) {
10+
int l = q.peek().getValue();
11+
int r = l;
12+
int size = q.size();
13+
for (int i = 0; i<size; i++) {
14+
TreeNode cur = q.peek().getKey();
15+
r = q.poll().getValue();
16+
if (cur.left!=null)
17+
q.offer(new Pair(cur.left, 2*r));
18+
if (cur.right!=null)
19+
q.offer(new Pair(cur.right, 2*r+1));
20+
}
21+
maxWidth = Math.max(maxWidth, r-l+1);
22+
}
23+
return maxWidth;
24+
}
25+
}

0 commit comments

Comments
 (0)