Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.
It is guaranteed that the answer will in the range of 32-bit signed integer.
Test Cases
Example 1:
Input: root = [1,3,null,5,3]
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
1
/ \
3 2
/ \ \
5 3 9
Example 2:
Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
1
/ \
3 2
/
5
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
Map<TreeNode, Integer> map = new HashMap<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
map.put(root, 1);
int maxWidth = 0, start=0, end=0;
while(!q.isEmpty()) {
int n = q.size();
for(int i=0; i<n; i++) {
TreeNode node = q.poll();
if (i==0) start = map.get(node);
if (i==n-1) end = map.get(node);
if (node.left != null) {
q.offer(node.left);
map.put(node.left, 2*map.get(node));
}
if (node.right != null) {
q.offer(node.right);
map.put(node.right, 1 + 2*map.get(node));
}
}
maxWidth = Math.max(maxWidth, end-start+1);
}
return maxWidth;
}
}
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
mp, q = {}, []
if root is None:
return 0
q.append(root)
start, end, mxw = 0, 0, 0
mp[root] = 1
while q:
size = len(q)
for i in range(size):
node = q.pop(0)
if i == 0:
start = mp[node]
if i == size-1:
end = mp[node]
if node.left:
q.append(node.left)
mp[node.left] = 2*mp[node]
if node.right:
q.append(node.right)
mp[node.right] = 2*mp[node] + 1
mxw = max(mxw, end-start+1)
return mxw