You are given the root of a binary tree. Add up every value in a node’s left subtree, then every value in its right subtree. How far apart those two totals are (ignoring the sign) is that node’s tilt. A missing subtree sums to 0, so a leaf has tilt 0.
Return the total of the tilts of every node in the tree. An empty tree has total 0.
Example 1
Input: root = [5, 3, 8, 1, null, 2, 6]
Output: 17
Why: node 3 tilts |1 − 0| = 1, node 8 tilts |2 − 6| = 4,
root tilts |4 − 16| = 12, leaves tilt 02 more examples and the constraints
Example 2
Input: root = [1, 2] Output: 2 Why: the root tilts |2 − 0| = 2; the leaf adds 0
Example 3
Input: root = [-4, 6, -1] Output: 7 Why: |6 − (−1)| = 7 at the root
Constraints
- 0 ≤ number of nodes ≤ 10,000
- −1,000 ≤ Node.val ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sum both sides at every nodeO(n²)
- One post-order passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work, 10,000 nodes in a chain | Verdict |
|---|---|---|---|
| Sum both sides at every node | O(n²) | Repeats the same sums | |
| One post-order pass | O(n) | Best; each node once |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree. No nodes, no tilt: return 0.
- One child only. The missing side counts as 0, as in Example 2.
- Negative values. Take the absolute value of the difference; a subtree sum can be negative.
- Deep chain. 10,000 nodes in a line: the from-scratch sums cost about n²/2, and the recursion goes 10,000 calls deep.
Common mistakes
- Using child values instead of whole subtree sums: the tilt compares entire subtrees.
- Returning the tilt from the recursion instead of the sum, so the parent has nothing to compare.
- Adding the node’s own value into its tilt; it belongs only in the sum it returns.
How to talk through it
- 1Clarify. Is the tilt about subtree sums or just the children? Does a missing child count as 0? Can values be negative?
- 2State the slow version. Sum both subtrees at every node: correct, but O(n²) on a chain because sums are recomputed.
- 3Spot the reuse. A parent’s sum is its value plus its children’s sums, so compute them bottom up.
- 4Return one thing, track another. The recursion returns the sum; a running total collects the tilts. O(n) time, O(h) space.
- 5Test out loud. Walk Example 1 and the one-child tree [1, 2].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?