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 - DFS Solution INPUT Binary Tree Structure 1 2 3 Input Array: 1 2 3 root = [1, 2, 3] 3 nodes total ALGORITHM STEPS 1 DFS Traversal Post-order: left, right, node 2 Calculate Subtree Sums Return sum of subtree values 3 Compute Tilt tilt = |leftSum - rightSum| 4 Accumulate Total Add each node's tilt to sum Calculations: Node 2: |0-0| = 0 Node 3: |0-0| = 0 Node 1: |2-3| = 1 Total: 0+0+1 = 1 FINAL RESULT Tree with Tilt Values 1 T=1 2 T=0 3 T=0 Output: 1 Sum of all tilts = 1 OK Key Insight: Use post-order DFS to compute subtree sums bottom-up. Each recursive call returns the sum of its subtree, while simultaneously accumulating the tilt value. This achieves O(n) time with a single traversal pass. Tilt at each node = |left_subtree_sum - right_subtree_sum|, then return node.val + left_sum + right_sum TutorialsPoint - Binary Tree Tilt | Optimal DFS - 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