public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public int sum(TreeNode root, List<Integer> tilt) {
if (root == null) return 0;
int leftSum = sum(root.left, tilt);
int rightSum = sum(root.right, tilt);
tilt.add(Math.abs(leftSum - rightSum));
return leftSum + rightSum + root.val;
}
public int findTilt(TreeNode root) {
List<Integer> tilt = new ArrayList<>();
sum(root, tilt);
int ans = 0;
for (int val: tilt) ans += val;
return ans;
}
}