Binary Tree Tilt - Problem

Given the root of a binary tree, return the sum of every tree node's tilt.

The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.

Input & Output

Example 1 — Simple Tree
$ Input: root = [1,2,3]
Output: 1
💡 Note: Node 2: tilt = |0-0| = 0, Node 3: tilt = |0-0| = 0, Node 1: tilt = |2-3| = 1. Total tilt = 0 + 0 + 1 = 1
Example 2 — Larger Tree
$ Input: root = [4,2,9,3,5,null,7]
Output: 15
💡 Note: Leaf nodes have tilt 0. Node 2: |3-5|=2, Node 9: |0-7|=7, Node 4: |10-16|=6. Total = 2+7+6 = 15
Example 3 — Single Node
$ Input: root = [21]
Output: 0
💡 Note: Single node has no children, so left sum = 0, right sum = 0, tilt = |0-0| = 0

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Binary Tree Tilt: Input [1,2,3] → Output 1123Input TreeLeft sum: 0Right sum: 0Tilt: 0Left sum: 0Right sum: 0Tilt: 0Left sum: 2Right sum: 3Tilt: |2-3| = 11Total TiltSum of all node tilts0 + 0 + 1 = 1Sum tilts
Understanding the Visualization
1
Input Tree
Binary tree with nodes [1,2,3]
2
Calculate Tilts
For each node, find |left_sum - right_sum|
3
Sum Tilts
Total tilt = sum of all individual node tilts
Key Takeaway
🎯 Key Insight: Use DFS post-order traversal to calculate subtree sums and accumulate tilts in a single pass
Asked in
Facebook 12 Amazon 8 Microsoft 6
125.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen