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 Ancestor83101614Node 8 is ancestor of node 1 (highlighted path)Difference: |8 - 1| = 7Output: 7
Understanding the Visualization
1
Input Tree
Binary tree with nodes containing integer values
2
Find Ancestor-Descendant Pairs
Identify all valid ancestor-descendant relationships
3
Calculate Maximum Difference
Find the pair with maximum absolute difference
Key Takeaway
🎯 Key Insight: Track min and max values along each path to find maximum ancestor-descendant difference in one pass
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