1. 程式人生 > >JavaScript刷LeetCode -- 563. Binary Tree Tilt

JavaScript刷LeetCode -- 563. Binary Tree Tilt

一、題目

  Given a binary tree, return the tilt of the whole tree.

  The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

  The tilt of the whole tree is defined as the sum of all nodes’ tilt.

  Example:

  Input: 
          1
        /   \
       2     3
  Output: 1
  Explanation: 
  Tilt of node 2 : 0
  Tilt of node 3 : 0
  Tilt of node 1 : |2-3| = 1
  Tilt of binary tree : 0 + 0 + 1 = 1

二、題目大意

   樹節點的傾斜度定義為所有左子樹節點值的總和與所有右子樹節點值的總和之間的絕對差,而整個樹的傾斜度定義為所有節點傾斜度之和,求出整個樹的傾斜度。

三、解題思路

  遞迴計算左右節點的差值,但是在遞迴的過程中,需要不斷向上返回該節點的子節點之和。

四、程式碼實現

const findTilt = root => {
  function helper (root) {
    if (!root) {
      return 0
    }
    const left = helper(root.left)
    const right = helper(root.right)

    sum += Math.abs(left - right)
    return root.val + left + right
  }
  let sum = 0
  helper(root)
  return sum
}

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