首页 > 其他 > 详细

563. Binary Tree Tilt

时间:2017-10-29 11:52:19      阅读:249      评论:0      收藏:0      [点我收藏+]


 

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:

  1. The sum of node values in any subtree won‘t exceed the range of 32-bit integer.
  2. All the tilt values won‘t exceed the range of 32-bit integer.

 

思路: 
这道题其实是要求 求出各个节点左右子树的差的绝对值,将这些绝对值求和并返回。 
左右子树的差 = | 左子树所有节点的值的和 - 右子树所有节点的值的和 | 
(刚开始没好好看题,只算了各个节点左右孩子的差,导致一直出错)

 1 class Solution {
 2     int SUM = 0;
 3     public int findTilt(TreeNode root) {
 4         postOrder(root);
 5         return SUM;
 6         
 7     }
 8       public int postOrder(TreeNode root) {
 9         if(root == null) return 0;
10         int left = postOrder(root.left);
11         int right =postOrder(root.right);
12     
13         SUM += Math.abs(left - right);
14  
15         return left + right+root.val;
16         
17     }
18 }

 

 

 

563. Binary Tree Tilt

原文:http://www.cnblogs.com/zle1992/p/7749464.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!