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.
- The number of nodes in the tree is in the range [0, 10⁴].
- -1000 <= Node.val <= 1000
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).
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.
Approach
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.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Returning the tilt instead of the sum
total += abs(left_sum - right_sum) return abs(left_sum - right_sum)
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
return left_sum + right_sum
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
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)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
total = 0
def subtree_sum(node):
...
total += abs(left_sum - right_sum)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.
Edge cases
subtree_sum(None) returns 0 at once, the total is never touched, and the answer is 0.
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.
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.
Complexity
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.