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
Note:
- The sum of node values in any subtree won‘t exceed the range of 32-bit integer.
- All the tilt values won‘t exceed the range of 32-bit integer.
題目標簽:Tree
這道題目給了我們一個二叉樹,要我們求出二叉樹的傾斜度。題目給了例子真的容易誤導人。一開始以為只要求2個children的差值,其實是要求left 和 right 各自的總和,包括加上它們自己,left 和 right 兩個總和值的差值。利用post order 遍歷二叉樹,post order 的順序是 左 右 根。這樣的話就可以求出根的sum,左和右都return了以後,加上它自己的值。但是這樣的recursively call 每次返回的都是一個點的sum 總值。我們需要求的是差值的總和。所以需要另外設一個res, 每次把差值加入res。
Java Solution:
Runtime beats 92.40%
完成日期:06/30/2017
關鍵詞:Tree
關鍵點:用post order去拿到每次left 和right 加上自己的總和;分清楚return的值並不是我們最終求的值,需要另外設置一個res,還有另一個help function
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution 11 { 12 int res = 0; 13 14 public int findTilt(TreeNode root) 15 { 16 postOrder(root); 17 18 return res; 19 } 20 21 public int postOrder(TreeNode node) 22 { 23 if(node == null) 24 return 0; 25 26 int left_sum = postOrder(node.left); 27 28 int right_sum = postOrder(node.right); 29 30 res += Math.abs(left_sum - right_sum); 31 32 return left_sum + right_sum + node.val; 33 } 34 }
參考資料:
https://leetcode.com/problems/binary-tree-tilt/#/solutions
LeetCode 563. Binary Tree Tilt (二叉樹的傾斜度)