package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func widthOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } maxWidth := 0 queue := []struct { node *TreeNode index int }{{root, 0}} for len(queue) > 0 { levelLength := len(queue) startIndex := queue[0].index endIndex := queue[levelLength-1].index if endIndex-startIndex+1 > maxWidth { maxWidth = endIndex - startIndex + 1 } newQueue := []struct { node *TreeNode index int }{} for i := 0; i < levelLength; i++ { current := queue[i] if current.node.Left != nil { newQueue = append(newQueue, struct { node *TreeNode index int }{current.node.Left, 2*(current.index - startIndex) + 1}) } if current.node.Right != nil { newQueue = append(newQueue, struct { node *TreeNode index int }{current.node.Right, 2*(current.index - startIndex) + 2}) } } queue = newQueue } return maxWidth } func main() { root := &TreeNode{Val: 1} root.Left = &TreeNode{Val: 2} root.Right = &TreeNode{Val: 3} root.Left.Left = &TreeNode{Val: 4} root.Right.Right = &TreeNode{Val: 5} fmt.Println(widthOfBinaryTree(root)) }
The maximum width is calculated by considering the position indices of nodes at each level. Here, the widest level is the last one with nodes 4 and 5 at positions 0 and 3 respectively, so width = 3 - 0 + 1 = 4.
Subtracting the start index at each level normalizes indices to prevent integer overflow and keeps the indices manageable while preserving relative positions for width calculation.
func widthOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } maxWidth := 0 queue := []struct { node *TreeNode index int }{{root, 1}} for len(queue) > 0 { levelLength := len(queue) startIndex := queue[0].index endIndex := queue[levelLength-1].index if endIndex-startIndex+1 > maxWidth { maxWidth = endIndex - startIndex + 1 } newQueue := []struct { node *TreeNode index int }{} for i := 0; i < levelLength; i++ { current := queue[i] if current.node.Left != nil { newQueue = append(newQueue, struct { node *TreeNode index int }{current.node.Left, 2*current.index}) } if current.node.Right != nil { newQueue = append(newQueue, struct { node *TreeNode index int }{current.node.Right, 2*current.index + 1}) } } queue = newQueue } return maxWidth }
The code does not normalize indices by subtracting the start index at each level, so indices can grow large and cause incorrect width calculations.
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Right = &TreeNode{Val: 4}
root.Right.Right = &TreeNode{Val: 5}
root.Left.Right.Left = &TreeNode{Val: 6}The maximum width is the largest distance between the leftmost and rightmost nodes at any level, counting null positions. Here, the widest level includes nodes at positions 0 and 4, so width = 5.
BFS visits nodes level by level, which is necessary to measure width at each level. Indexing nodes tracks their positions including gaps caused by missing nodes, allowing accurate width calculation.