这里采用同层次遍历相同的策略,同样是用数组存放结点,区别在于增加了结点所在当前层的序号,这个根据父节点的序号计算(左节点是父节点序号的2倍,右节点是父节点序号的2倍+1)。
需要注意的是,计算宽度的时候别忘了➕1!!!
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 借助一个记录序列号的结构体来计算二叉树的最大宽度
type item struct{
idx int
*TreeNode
}
func widthOfBinaryTree(root *TreeNode) int {
if root == nil {
return 0
}
// 初始宽度为1
ans, q := 1, []item{{0,root}}
for len(q)>0 {
// 计算当前层的最大宽度,注意还要加一
if l := q[len(q)-1].idx - q[0].idx + 1; l > ans {
ans = l
}
// 存放下一层的结构体(根据当前层结点的索引去计算左右子节点上的索引编号)
temp := []item{}
for _, p := range q{
if p.Left != nil {
temp = append(temp, item{p.idx*2, p.Left})
}
if p.Right != nil {
temp = append(temp, item{p.idx*2+1, p.Right})
}
}
q = temp
}
return ans
}