LeetCode #563 Easy

Binary Tree Tilt

Binary Tree Tilt is LeetCode 563 (Easy). Given the root of a binary tree, return the sum of the tilts of all its nodes.

  • A node's tilt is the absolute difference between the sum of every value in its left subtree and the sum of every value in its right subtree.
  • A missing subtree counts as a sum of 0.

The tree has up to 10,000 nodes, so the target is one pass over the tree: O(n) time.

Constraints
  • The number of nodes in the tree is in the range [0, 10⁴].
  • -1000 <= Node.val <= 1000
treedfsrecursion
Open on LeetCode ↗
02

Intuition

A node's tilt needs two numbers: the total of its left subtree and the total of its right subtree. Those totals are exactly what its two children can report once they are finished. So walk the tree in postorder and let every call return its subtree sum, not its tilt:

  • Up the tree: each call returns its own value plus both child sums, which is the one number its parent needs.
  • On the side: each call adds |left sum − right sum| to a single running total.

Every node is visited once and every subtree sum is built once, from sums already computed below it, so the whole answer costs O(n).

How to spot this pattern

When a node's answer depends on totals over its whole subtrees, and the final result adds up something from every node, use a postorder walk whose return value (the subtree sum) differs from what it collects (the tilt). Diameter of Binary Tree has the same split: it returns heights while it records the longest path.

03

Approach

Try it first

Before reading on, take the tree [4, 2, 9, 3, 5, null, 7]. Write down what node 2 must learn from its children before it can work out its tilt, and which single number it must pass up to node 4. Aim for one pass over the tree.

1

Return 0 for a missing child

A missing subtree holds no values, so its sum is 0. This lets a leaf, or a node with only one child, use the same tilt formula as every other node, with no special case.

2

Total both subtrees first

Call the helper on the left child, then on the right child, before doing anything at the current node. This is postorder: a node can measure how lopsided it is only after both of its subtrees have been added up.

3

Add this node's tilt to the running total

Add abs(left_sum - right_sum) to a total that lives outside the helper: a nonlocal variable in Python, a field in C++ and Java. Every node runs this line exactly once, so the total ends up holding every node's tilt.

4

Return the whole subtree's sum

Return node.val + left_sum + right_sum. The parent uses this number as one side of its own tilt, so it has to include every value in this subtree.

5

Run it from the root

Call the helper on the root and return the running total. The sum the root's call returns is the sum of the entire tree, which nothing needs, so it is ignored.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findTilt(self, root: Optional[TreeNode]) -> int:
▶3 total = 0
▶4 
▶5 def subtree_sum(node):
▶6 nonlocal total
▶7 if not node:
▶8 return 0
▶9 left_sum = subtree_sum(node.left)
▶10 right_sum = subtree_sum(node.right)
▶11 total += abs(left_sum - right_sum)
▶12 return node.val + left_sum + right_sum
▶13 
▶14 subtree_sum(root)
▶15 return total
123left sumright sumtiltsends uptotal tilt0total starts at 0
total0
Start with a total of 0. The walk is postorder: a node is handled only after both of its subtrees, because its tilt needs both subtree sums.
123left sumright sumtiltsends up0−0→0total tilt0=0leaf 2: both sides empty → tilt 0
left_sum0
right_sum0
total0
Node 2 is a leaf, so both of its subtrees are empty and sum to 0. Its tilt is the gap between them, 0, and it goes straight into the running total, which is now 0.
12sum 23left sumright sumtiltsends up0−0→02total tilt0=0node 2 sends sum 2 up to 1
returns2
Node 2 returns 2: its own value plus everything below it. Node 1 will use this number as one side of its own tilt, so it must be the subtree's total, not its tilt.
12sum 23left sumright sumtiltsends up0−0→0total tilt0+0=0leaf 3: both sides empty → tilt 0
left_sum0
right_sum0
total0
Node 3 is a leaf, so both of its subtrees are empty and sum to 0. Its tilt is the gap between them, 0, and it goes straight into the running total, which is now 0.
12sum 23sum 3left sumright sumtiltsends up0−0→03total tilt0+0=0node 3 sends sum 3 up to 1
returns3
Node 3 returns 3: its own value plus everything below it. Node 1 will use this number as one side of its own tilt, so it must be the subtree's total, not its tilt.
12sum 23sum 3left sumright sumtiltsends up2−3→1total tilt0+0+1=1node 1 leans by 1 → total 1
left_sum2
right_sum3
total1
Its left subtree sent up 2 and its right subtree sent up 3. Its tilt is the gap between them, 1, and it goes straight into the running total, which is now 1.
1sum 62sum 23sum 3left sumright sumtiltsends up2−3→1total tilt0+0+1=1the root's sum, 6, is not needed
returns6
The root returns 6, the sum of the whole tree. Nothing sits above the root, so this number is thrown away; the answer is the running total.
1sum 62sum 23sum 3left sumright sumtiltsends uptotal tilt0+0+1=1answer: 1
answer1
Every node has added its tilt once, so the total, 1, is the answer. Each subtree sum was built from the sums its children returned, never by re-walking the subtree.
05

Common pitfalls

Returning the tilt instead of the sum

✗ Wrong
total += abs(left_sum - right_sum)
return abs(left_sum - right_sum)
✓ Right
total += abs(left_sum - right_sum)
return node.val + left_sum + right_sum

The parent then compares two tilts instead of two subtree totals. On [1, 2, 3] both children are leaves with tilt 0, so the root sees 0 against 0 and adds nothing. Its real tilt is |2 − 3| = 1, so the answer should be 1, not 0.

Leaving the node's own value out of the sum

✗ Wrong
return left_sum + right_sum
✓ Right
return node.val + left_sum + right_sum

Every leaf then reports 0 to its parent, and every sum built on top of it is 0 as well. On [1, 2, 3] the root again sees 0 against 0 and the code returns 0 instead of 1.

Adding up each subtree again at every node

✗ Wrong
def findTilt(self, root):
    if not root:
        return 0
    tilt = abs(tree_sum(root.left) - tree_sum(root.right))
    return tilt + self.findTilt(root.left) + self.findTilt(root.right)
✓ Right
left_sum = subtree_sum(node.left)
right_sum = subtree_sum(node.right)

The answers are right, but every node walks its whole subtree again. On a chain of 10,000 nodes that is about 50 million node visits instead of 10,000, because the bottom node is re-added by every node above it.

Keeping the running total in a plain local variable

✗ Wrong
total = 0
def subtree_sum(node):
    ...
    total += abs(left_sum - right_sum)
✓ Right
total = 0
def subtree_sum(node):
    nonlocal total
    ...

Python sees the += and treats total as a new variable inside the helper, so the first non-empty tree, even [1], crashes with UnboundLocalError. Passing the total as an ordinary int argument in C++ or Java fails quietly instead: each call changes its own copy and the answer stays 0.

06

Edge cases

Empty tree

subtree_sum(None) returns 0 at once, the total is never touched, and the answer is 0.

Negative values

Subtree sums can be negative, so take abs of the difference, never of each sum alone. A left sum of −5 and a right sum of 5 is a tilt of 10, not 0.

A chain of 10,000 nodes

The recursion is 10,000 calls deep. C++ and Java handle that. Plain Python stops at a default depth of 1,000, so raise it with sys.setrecursionlimit if your runner keeps the default.

07

Complexity

Time
O(n)
Space
O(h)
Each node is entered once and does constant work besides its two child calls. The call stack holds one frame per level of the tree: about log n frames when the tree is balanced, n when it is a chain.
08

Binary Tree Tilt FAQ

Is the tilt of a binary tree the same as the tilt of its root?

No. The root's tilt compares only its two subtrees; the answer adds the tilts of all the nodes. In [4, 2, 9, 3, 5, null, 7] the root's tilt is |10 − 16| = 6, while nodes 2 and 9 add 2 and 7, so the answer is 15.

Can it be written without a variable outside the recursion?

Yes. Return a pair from each call: the subtree's sum and the total tilt inside that subtree. A node adds its children's totals to its own tilt. It is still O(n); the outside variable just keeps each return value to a single number.