563. Binary Tree Tilt

网友投稿 705 2022-10-09

563. Binary Tree Tilt

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 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.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution private int sum = 0; public int findTilt(TreeNode root) { helper(root); return sum; } private int helper(TreeNode root) { if (root == null) return 0; int left = helper(root.left); int right = helper(root.right); sum += Math.abs(left - right); return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:561. Array Partition I
下一篇:Face2FaceTranslator- 面对面翻译小程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~