class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function widthOfBinaryTree(root: TreeNode | null): number {
if (!root) return 0;
let maxWidth = 0;
// Queue holds pairs of node and its index
const queue: Array<[TreeNode, number]> = [[root, 0]];
while (queue.length > 0) {
const levelLength = queue.length;
const levelIndices = queue.map(pair => pair[1]);
const levelMin = levelIndices[0];
const levelMax = levelIndices[levelIndices.length - 1];
maxWidth = Math.max(maxWidth, levelMax - levelMin + 1);
for (let i = 0; i < levelLength; i++) {
const [node, index] = queue.shift()!;
// Normalize index to prevent overflow
const normalizedIndex = index - levelMin;
if (node.left) queue.push([node.left, 2 * normalizedIndex]);
if (node.right) queue.push([node.right, 2 * normalizedIndex + 1]);
}
}
return maxWidth;
}
// Driver code
const root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, null, new TreeNode(5))
);
console.log(widthOfBinaryTree(root));const queue: Array<[TreeNode, number]> = [[root, 0]];
Initialize queue with root node and index 0 to track positions
const levelIndices = queue.map(pair => pair[1]);
Collect indices of nodes at current level to calculate width
const levelMin = levelIndices[0];
const levelMax = levelIndices[levelIndices.length - 1];
Find leftmost and rightmost indices to measure width
maxWidth = Math.max(maxWidth, levelMax - levelMin + 1);
Update maximum width if current level is wider
const [node, index] = queue.shift()!;
const normalizedIndex = index - levelMin;
Remove node from queue and normalize index to avoid large numbers
if (node.left) queue.push([node.left, 2 * normalizedIndex]);
if (node.right) queue.push([node.right, 2 * normalizedIndex + 1]);
Add children to queue with calculated indices to keep track of positions