1. 程式人生 > >JavaScript刷LeetCode -- 662. Maximum Width of Binary Tree【Medium】

JavaScript刷LeetCode -- 662. Maximum Width of Binary Tree【Medium】

一、題目

  Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

  The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

二、題目大意

  二叉樹的寬度定義為端節點之間的長度,並且其中端節點之間的空節點也被計算在長度之內。

三、解題思路

  這道題目採用分層遍歷的方法獲取每一層的最大寬度,最終得出樹的最大寬度,但是在樹中是存在空節點的,所以這裡採用記錄節點下標的方式,計算端節點下標的差值得到當前層級的寬度。

四、程式碼實現

const widthOfBinaryTree = root => {
  if (!root) {
    return 0
  }
  const MAX = Number.MAX_SAFE_INTEGER
  const q = [ [root, 1] ]
  let ans = 1
  while (q.length) {
    ans = Math.max(q[q.length - 1][1] - q[0][1] + 1, ans)
    const max = q.length
    for (let i = 0; i < max; i++) {
      const x = q.shift()
      const [item, index] = x
      if (item.left) {
        // 這裡需要考慮下標可能會超出最大值
        q.push([item.left, (2 * index) % MAX])
      }
      if (item.right) {
        q.push([item.right, (2 * index + 1) % MAX])
      }
    }
  }
  return ans
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。