-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
29 lines (23 loc) · 804 Bytes
/
Solution.java
File metadata and controls
29 lines (23 loc) · 804 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
/*
@lc id : 662 Maximum Width of Binary Tree
@author : rohit
@date : 08/07/2020
@url : https://leetcode.com/problems/maximum-width-of-binary-tree/
*/
class Solution {
int maxWidth;
HashMap<Integer, Integer> leftMostPosition;
public void getWidth(TreeNode root, int depth, int position){
if(root == null) return;
leftMostPosition.computeIfAbsent(depth, x -> position);
maxWidth = Math.max(maxWidth, position - leftMostPosition.get(depth) + 1);
getWidth(root.left, depth+1, position*2);
getWidth(root.right, depth+1, position*2 + 1);
}
public int widthOfBinaryTree(TreeNode root) {
maxWidth = 0;
leftMostPosition = new HashMap<>();
getWidth(root, 0, 0);
return maxWidth;
}
}