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:

  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.

 


 

题目标签: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 算法题目列表 - LeetCode Algorithms Questions List

posted @   Jimmy_Cheng  阅读(1223)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?
点击右上角即可分享
微信分享提示