码迷,mamicode.com
首页 > 其他好文 > 详细

563. Binary Tree Tilt

时间:2017-10-22 21:46:34      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:btree   code   倾斜   out   fine   res   color   not   exp   

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.

题目含义: 这道题目给了我们一个二叉树,要我们求出二叉树的倾斜度。题目给了例子真的容易误导人。一开始以为只要求2个children的差值,其实是要求left 和 right 各自的总和,包括加上它们自己,left 和 right 两个总和值的差值。

 1     private int result=0;
 2     private int postOrder(TreeNode node)
 3     {
 4         if (node == null) return 0;
 5         int leftSum = postOrder(node.left);
 6         int rightSum = postOrder(node.right);
 7         result += Math.abs(leftSum-rightSum);
 8         return leftSum + rightSum +node.val;
 9     }
10     public int findTilt(TreeNode root) {
11        //        这道题目给了我们一个二叉树,要我们求出二叉树的倾斜度。题目给了例子真的容易误导人。一开始以为只要求2个children的差值,其实是要求left 和 right 各自的总和,包括加上它们自己,left 和 right 两个总和值的差值。利用post order 遍历二叉树,post order 的顺序是 左 右 根。这样的话就可以求出根的sum,左和右都return了以后,加上它自己的值。但是这样的recursively call 每次返回的都是一个点的sum 总值。我们需要求的是差值的总和。所以需要另外设一个res, 每次把差值加入res。
12         postOrder(root);
13         return result;
14     }

 

563. Binary Tree Tilt

标签:btree   code   倾斜   out   fine   res   color   not   exp   

原文地址:http://www.cnblogs.com/wzj4858/p/7710731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!