The tilt of a tree node is defined as the absolute difference between the sum of all node values in its left subtree and the sum of all node values in its right subtree. The total tilt of a binary tree is the sum of the tilts of all its nodes. The Binary Tree Tilt coding problem asks you to calculate this total sum.
This problem, often seen in Amazon and Indeed interviews, is a great test of recursive data aggregation. It requires you to calculate two different things simultaneously: the sum of nodes (to pass up to the parent) and the tilt (to add to a global total). It’s an exercise in maintaining a running total while performing a standard tree traversal.
This problem is solved using a Post-order Traversal (DFS). To calculate the tilt of a node, you must first know the sum of its left and right subtrees. Therefore, your recursive function should return the total sum of the subtree rooted at the current node (left_sum + right_sum + node.val). While calculating this, you compute the tilt (abs(left_sum - right_sum)) and add it to a global variable.
Consider a simple tree:
4
/
2 9
/ \
3 5 7
A common pitfall is confusing the "sum of nodes" with the "sum of tilts." The recursive function should return the sum of the values in the subtree, not the tilt. Another mistake is forgetting that tilt is the absolute difference—candidates sometimes forget to use an abs() function, leading to incorrect results when one subtree is larger than the other.
When a problem asks for a value based on subtree sums, always think "Post-order DFS." Practice returning one value while updating a global state, as this is a recurring theme in tree-based interview questions.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Evaluate Boolean Binary Tree | Easy | Solve | |
| Sum of Root To Leaf Binary Numbers | Easy | Solve | |
| Leaf-Similar Trees | Easy | Solve | |
| Balanced Binary Tree | Easy | Solve | |
| Diameter of Binary Tree | Easy | Solve |