#563
Binary Tree Tilt
EasyTreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution uses a single traversal of the tree to calculate both the tilt and the sum of the subtree values. This avoids redundant calculations and improves efficiency.
⚙️
Algorithm
4 steps- 1Step 1: Traverse the tree using a depth-first search (DFS).
- 2Step 2: For each node, calculate the sum of its left and right subtrees in one pass.
- 3Step 3: Calculate the tilt and add it to a global sum during the traversal.
- 4Step 4: Return the total tilt after the traversal is complete.
solution.py20 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def findTilt(self, root: TreeNode) -> int:
9 def dfs(node):
10 if not node:
11 return 0
12 left_sum = dfs(node.left)
13 right_sum = dfs(node.right)
14 tilt = abs(left_sum - right_sum)
15 self.total_tilt += tilt
16 return left_sum + right_sum + node.val
17
18 self.total_tilt = 0
19 dfs(root)
20 return self.total_tiltℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Using a single traversal reduces redundant calculations.
- 2Understanding tree structure helps in visualizing subtree sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.