417. Binary Tree Tilt
Every node of a binary tree has a tilt: the absolute difference between the sum of all values in its left subtree and the sum of all values in its right subtree. A missing subtree contributes 0, so a leaf's tilt is always 0.
Your function receives root, the root of a binary tree (possibly empty), and returns one integer: the sum of the tilts of every node in the tree.
Example 1:
Input: root = [5, 2, 9, 1, 4, null, 3]
Output: 11
Explanation: The three leaves tilt 0. Node 2 tilts |1 − 4| = 3, node 9 tilts |0 − 3| = 3 (its left subtree is empty), and the root tilts |(2+1+4) − (9+3)| = |7 − 12| = 5. Summed: 3 + 3 + 5 = 11.
Example 2:
Input: root = [2, 3, 5]
Output: 2
Explanation: Both leaves tilt 0 and the root tilts |3 − 5| = 2.
Constraints:
- The number of nodes is in the range [0, 10⁴].
- -1000 ≤ Node.val ≤ 1000
Hints:
A node's tilt needs its subtree *sums*, not its subtree tilts — two different quantities are flowing through the tree. Which one should the recursion return?
Do one postorder walk: have the helper return the sum of its subtree (node value + left sum + right sum), and as a side effect add |left sum − right sum| to a running total. Each node is visited once.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: root = [5, 2, 9, 1, 4, null, 3]
Expected output: 11