563. Binary Tree Tilt
来源:互联网 发布:淘宝倒卖赚差价的生意 编辑:程序博客网 时间:2024/05/19 17:24
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 3Output: 1Explanation: Tilt of node 2 : 0Tilt of node 3 : 0Tilt of node 1 : |2-3| = 1Tilt 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.
方法1:递归的方式,一边累加tilt的值,一边求左、右子树的和。代码如下。一个很明显的问题是,在求左右子树和时,树被遍历了多次。比如,求1的左右子树和时,需要遍历2、4、5、3;在求2的左右子树和时需要遍历4、5,可见4、5被遍历了两遍。
public static int findTilt(TreeNode root) { if(root == null) { return 0; } return findTilt(root.left) + findTilt(root.right) + Math.abs(sum(root.left) - sum(root.right));}public static int sum(TreeNode root) { if(root == null) { return 0; } return root.val + sum(root.left) + sum(root.right); }
改进:
设置一个全局变量tilt,用于记录tilt的累加值,在求左右子树和的过程中,累加tilt
int tilt = 0; public int findTilt(TreeNode root) { sum(root); return tilt; } public int sum(TreeNode root) { if(root == null) { return 0; } int l = sum(root.left); int r = sum(root.right); tilt += Math.abs(l - r); return l + r + root.val; }
0 0
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt **
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- LeetCode 563. Binary Tree Tilt
- LeetCode | 563. Binary Tree Tilt
- [LeetCode]563. Binary Tree Tilt
- ios开发之NSPathUtilities
- java反射中getDeclaredMethods和getMethods的区别
- Caffe中权值初始化方法
- [李景山php] 深入理解PHP内核[读书笔记]--第二章:用户代码执行--opcode处理函数查找
- 3.2 JS 变量提升&&函数参数
- 563. Binary Tree Tilt
- Batch Normalization梯度反向传播推导
- 2017-05-09 总结
- Android N 多窗口的设计
- 服务的基本用法-1
- ios 蓝牙开发总结
- hihoCoder 1518 : 最大集合
- 熔断器设计模式
- 在 Ubuntu 中手动安装任何版本的 Firefox