Binary Tree Tilt
Sum the tilt of every node, where a node's tilt is |sum(left subtree) - sum(right subtree)|.
Open on LeetCode ↗Intuition
Trying to make the recursion return the tilt directly is the wrong instinct -- the recursion's job is to return the SUBTREE SUM, because that is what a parent node needs to compute ITS OWN tilt. The tilt itself is a side quantity: compute it at each node from the two subtree sums just returned, then accumulate it into an outer running total, separately from whatever gets passed back up the call stack. Two different values are flowing in two different directions at once -- sums flow upward through return values, while the tilt total accumulates sideways as a side effect -- and keeping them distinct is the entire problem.
Approach
Recurse for subtree sums
Each call to subtreeSum(node) returns node.val + subtreeSum(node.left) + subtreeSum(node.right) -- purely the sum, nothing about tilt.
Compute and accumulate tilt as a side effect
At each node, tilt = abs(leftSum - rightSum); add it into a total tracked outside the recursion's return value (an instance variable or nonlocal counter).
Return only the sum upward
The function returns leftSum + rightSum + node.val so the parent can use it -- the tilt total is never part of what gets returned.
Solution & live demo
Edge cases
subtreeSum(None) returns 0, contributing nothing to any tilt.
Both subtree sums are 0, so its tilt is 0 -- but it still returns its own value upward.
Each node's tilt is large since one side is always 0, but the sums still combine correctly bottom-up.
Sums and tilt (via abs) still compute correctly; no special casing needed.