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.
I think that explanation and example provided are not sufficient. You need to have a biger tree to explain this problem:
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : 15
Explanation:
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
int sum = 0;
public int FindTilt(TreeNode root) {
if(root==null){
return 0;
}
if(root.left ==null && root.right == null){
return root.val;
}
int leftSum = TotalSum(root.left);
int rightSum = TotalSum(root.right);
sum += Math.Abs(leftSum-rightSum);
FindTilt(root.left);
FindTilt(root.right);
return sum;
}
private int TotalSum(TreeNode root){
if(root==null){
return 0;
}
if(root.left == null && root.right==null){
return root.val;
}
int leftSum = TotalSum(root.left);
int rightSum = TotalSum(root.right);
return root.val+leftSum+rightSum;
}
}
Time Complexity: O(n)
Space Complexity: O(1)