using System;
using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public int WidthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int maxWidth = 0;
var queue = new Queue<(TreeNode node, int index)>();
queue.Enqueue((root, 0));
while (queue.Count > 0) {
int levelSize = queue.Count;
int levelHeadIndex = queue.Peek().index; // index of first node at this level
int firstIndex = 0, lastIndex = 0;
for (int i = 0; i < levelSize; i++) {
var (node, index) = queue.Dequeue();
int currIndex = index - levelHeadIndex; // normalize to prevent overflow
if (i == 0) firstIndex = currIndex;
if (i == levelSize - 1) lastIndex = currIndex;
if (node.left != null) queue.Enqueue((node.left, currIndex * 2));
if (node.right != null) queue.Enqueue((node.right, currIndex * 2 + 1));
}
int width = lastIndex - firstIndex + 1;
if (width > maxWidth) maxWidth = width;
}
return maxWidth;
}
public static void Main() {
// Build tree: 1
// / \
// 3 2
// / \
// 5 9
// / \
// 6 7
TreeNode 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))));
Solution sol = new Solution();
int maxWidth = sol.WidthOfBinaryTree(root);
Console.WriteLine(maxWidth);
}
}queue.Enqueue((root, 0));
Start BFS with root node at index 0
int levelHeadIndex = queue.Peek().index;
Record index of first node at current level to normalize indices
int currIndex = index - levelHeadIndex;
Normalize current node index to prevent integer overflow
if (node.left != null) queue.Enqueue((node.left, currIndex * 2));
Assign left child index as 2 * current index
if (node.right != null) queue.Enqueue((node.right, currIndex * 2 + 1));
Assign right child index as 2 * current index + 1
int width = lastIndex - firstIndex + 1;
Calculate width of current level including gaps
if (width > maxWidth) maxWidth = width;
Update maximum width if current level is wider