Binary Tree Tilt - Problem
Given the root of a binary tree, calculate the tilt of the entire tree. The tilt of a node is defined as the absolute difference between the sum of all values in its left subtree and the sum of all values in its right subtree.
Key Points:
- If a node has no left child, the left subtree sum is
0 - If a node has no right child, the right subtree sum is
0 - The tree tilt is the sum of all individual node tilts
Example: For a tree with root value 1, left child 2, and right child 3, the tilt of root is |2 - 3| = 1, and the tilts of leaves are |0 - 0| = 0, so total tilt is 1 + 0 + 0 = 1.
Input & Output
example_1.py — Simple Tree
$
Input:
[1,2,3]
›
Output:
1
💡 Note:
Root tilt = |sum([2]) - sum([3])| = |2-3| = 1. Left child tilt = |0-0| = 0. Right child tilt = |0-0| = 0. Total tilt = 1+0+0 = 1.
example_2.py — Complex Tree
$
Input:
[4,2,9,3,5,null,7]
›
Output:
15
💡 Note:
Root tilt = |sum([2,3,5]) - sum([9,7])| = |10-16| = 6. Node 2 tilt = |3-5| = 2. Node 9 tilt = |0-7| = 7. Others have tilt 0. Total = 6+2+7+0+0+0 = 15.
example_3.py — Single Node
$
Input:
[21]
›
Output:
0
💡 Note:
Single node has no children, so left sum = 0, right sum = 0. Tilt = |0-0| = 0.
Visualization
Tap to expand
Understanding the Visualization
1
Post-order Traversal
Visit children first, then process current node to ensure subtree sums are available
2
Calculate Subtree Sums
For each node, get sum of left subtree and sum of right subtree from recursive calls
3
Compute Node Tilt
Tilt = |leftSum - rightSum| measures the imbalance at current node
4
Accumulate Total
Add current node's tilt to running total and return subtree sum to parent
Key Takeaway
🎯 Key Insight: By using post-order DFS traversal, we calculate each subtree sum exactly once while accumulating tilt values, achieving optimal O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Visit each node exactly once in the tree
✓ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h, O(log n) for balanced tree, O(n) worst case
✓ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 104]
- -1000 ≤ Node.val ≤ 1000
- Tree can have null children at any level
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code