#1026
Maximum Difference Between Node and Ancestor
MediumTreeDepth-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)
Instead of checking all ancestors for every node, we can use a depth-first search (DFS) to track the minimum and maximum values encountered along the path from the root to each node. This allows us to compute the maximum difference in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS traversal of the tree, starting from the root.
- 2Step 2: At each node, update the minimum and maximum values encountered on the path from the root.
- 3Step 3: Calculate the difference between the current node's value and the minimum/maximum values, and update the maximum difference accordingly.
solution.py16 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def maxAncestorDiff(root):
9 def dfs(node, min_val, max_val):
10 if not node:
11 return max_val - min_val
12 min_val = min(min_val, node.val)
13 max_val = max(max_val, node.val)
14 return max(dfs(node.left, min_val, max_val), dfs(node.right, min_val, max_val))
15
16 return dfs(root, root.val, root.val)ℹ
Complexity note: The time complexity is linear 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.
- 1The maximum difference can be efficiently calculated using DFS by tracking min and max values.
- 2Understanding the ancestor relationship in trees is crucial for solving this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.