首页 > 代码库 > LeetCode 563. Binary Tree Tilt (二叉树的倾斜度)
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 (二叉树的倾斜度)