It is kinda intuitive that a recursive approach fits this problem perfectly. The main challenge lies in that we have to seek out a way to calculate the tilt of a node and sum all the nodes below this nodes at the same time.
class Solution {
int res = 0;
public int findTilt(TreeNode root) {
find(root);
return res;
}
public int find(TreeNode root){
if(root == null) return 0;
int left = find(root.left);
int right = find(root.right);
res += Math.abs(left - right);
return left + right + root.val;
}
}
In the solution above, we recursively sum the value of nodes we are looking for. First of all, we find the sum of left sub tree recursively, then the right one. We add the absolute value of the difference to a global variable, then return the sum to the upper level in the stack. This is a post order traversal.