563. Binary Tree Tilt
Posted 张乐乐章
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
思路:
这道题其实是要求 求出各个节点左右子树的差的绝对值,将这些绝对值求和并返回。
左右子树的差 = | 左子树所有节点的值的和 - 右子树所有节点的值的和 |
(刚开始没好好看题,只算了各个节点左右孩子的差,导致一直出错)
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的主要内容,如果未能解决你的问题,请参考以下文章