class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function widthOfBinaryTree(root) {
if (!root) return 0;
let maxWidth = 0;
// Queue holds pairs: [node, index]
const queue = [[root, 0]];
while (queue.length > 0) {
const levelLength = queue.length;
const levelIndices = [];
for (let i = 0; i < levelLength; i++) {
const [node, index] = queue.shift();
levelIndices.push(index);
if (node.left) queue.push([node.left, 2 * index + 1]);
if (node.right) queue.push([node.right, 2 * index + 2]);
}
// Width = last index - first index + 1
const width = levelIndices[levelIndices.length - 1] - levelIndices[0] + 1;
if (width > maxWidth) maxWidth = width;
}
return maxWidth;
}
// Driver code to build tree and test
const root = new TreeNode(1,
new TreeNode(3,
new TreeNode(5,
new TreeNode(6), null
), null
),
new TreeNode(2,
null,
new TreeNode(9,
null,
new TreeNode(7)
)
)
);
console.log(widthOfBinaryTree(root));const queue = [[root, 0]];
Initialize queue with root node and index 0 to track positions
for (let i = 0; i < levelLength; i++) { const [node, index] = queue.shift();
Process each node in current level with its index
if (node.left) queue.push([node.left, 2 * index + 1]);
Assign left child index as 2*parent_index+1
if (node.right) queue.push([node.right, 2 * index + 2]);
Assign right child index as 2*parent_index+2
const width = levelIndices[levelIndices.length - 1] - levelIndices[0] + 1;
Calculate width of current level including gaps
if (width > maxWidth) maxWidth = width;
Update maximum width if current level is wider