leetcode-662

114 阅读1分钟

题目描述:具体描述见原题,简单来说就是求每层最左和最右之间节点的距离,并返回这些距离值中的最大值。

解题思路:还是利用BFS,遍历每一层节点,计算每层最左边节点和最右边节点位置差值,动态更新差值。由于本题中并没有使用节点值,所以可以用Val字段记录节点在每层中的位置,根据满二叉树结构,如果父节点位置为i,那么左子树在对应层位置为2*i,右子树在对应层位置为2*\i+1。具体过程见代码。

具体代码:


func widthOfBinaryTree(root *TreeNode) int {
   queue, res := make([]*TreeNode, 0), 0
   if root == nil {
      return res
   }
   if root.Left == nil && root.Right == nil {
      return res
   }
   queue = append(queue, &TreeNode{0, root.Left, root.Right})
   for len(queue) != 0 {
      temp := make([]*TreeNode, 0)
      for _, q := range queue{
         if q.Left != nil {
            temp = append(temp, &TreeNode{Val:q.Val*2, Left:q.Left.Left, Right:q.Left.Right}) // 重新构造左节点,将节点值替换为节点位置
         }
         if q.Right != nil {
            temp = append(temp, &TreeNode{Val:q.Val*2+1, Left:q.Right.Left, Right:q.Right.Right}) // 重新构造右节点,将节点值替换为节点位置
         }
      }
      if len(temp) == 0 { // 如果temp为空,代表遍历结束
         return res
      }
      if len(temp) > 1 { // 当前层存在两个及两个以上节点,更新差值
         res = max(res, temp[len(temp)-1].Val - temp[0].Val + 1)
      } else {
         res = max(res, 1) // 当前层只存在一个节点,更新差值
      }
      queue = temp // 逐层遍历
   }
   return res
}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

补充说明:最近遗传算法看的有点头大,将粒子群算法引入可以解决的问题及论证还得再看,明天估计依旧是BFS。