Maximum Difference Between Node and Ancestor - Problem

Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.

A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.

Input & Output

Example 1 — Basic Tree
$ Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
💡 Note: The maximum difference is between node 8 and node 1: |8 - 1| = 7. Node 8 is an ancestor of node 1.
Example 2 — Simple Tree
$ Input: root = [1,null,2,null,0,3]
Output: 3
💡 Note: The maximum difference is between node 1 and node 3: |1 - 3| = 2, or between node 2 and node 3: |2 - 3| = 1. Actually, it's between node 1 and node 0: |1 - 0| = 1, then node 0 and node 3: |0 - 3| = 3.
Example 3 — Single Path
$ Input: root = [5,4,null,1]
Output: 4
💡 Note: Path: 5 → 4 → 1. Maximum difference is |5 - 1| = 4.

Constraints

  • The number of nodes in the tree is in the range [2, 5000]
  • 0 ≤ Node.val ≤ 105

Visualization

Tap to expand
Maximum Difference Between Node and Ancestor INPUT Binary Tree Structure 8 3 10 1 6 14 4 7 13 [8,3,10,1,6,null,14,null,null,4,7,13] a is ancestor of b Find max |a.val - b.val| ALGORITHM STEPS 1 DFS Traversal Track min/max from root to current node path 2 Update Min/Max At each node, update curMin = min(curMin, val) curMax = max(curMax, val) 3 Leaf Node Check At leaf: compute diff diff = curMax - curMin 4 Return Maximum Return max diff found across all paths Path: 8 --> 3 --> 1 min=1, max=8 diff = 8 - 1 = 7 Maximum found! FINAL RESULT Highlighted: Max Diff Path 8 3 10 1 6 Output: 7 |8 - 1| = 7 Node 8 is ancestor of 1 Path: 8 --> 3 --> 1 OK - Maximum difference! Key Insight: Instead of comparing every ancestor-descendant pair (O(n^2)), we track the running min and max values along each root-to-leaf path. At leaf nodes, the difference (max - min) gives the maximum possible difference for that path. This achieves O(n) time complexity with O(h) space (h = height). TutorialsPoint - Maximum Difference Between Node and Ancestor | DFS with Min/Max Tracking
Asked in
Amazon 12 Google 8 Microsoft 6
98.2K Views
Medium Frequency
~15 min Avg. Time
2.8K 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