1. 程式人生 > >563. Binary Tree Tilt 子節點差的絕對值之和

563. Binary Tree Tilt 子節點差的絕對值之和

complex 正常 spa 結構 values num tween absolut 英文

[抄題]:

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

[暴力解法]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思維問題]:

以為要用hashmap把每個點的距離差都存起來,但其實用traverse的參數 就能實現自動記錄

[一句話思路]:

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

[復雜度]:Time complexity: O() Space complexity: O()

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

理解DFS的返回值適用於所有點,ans[0]的返回值只適用於root一個點

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

563. Binary Tree Tilt 子節點差的絕對值之和