AlgoInsight

DSA problem

Maximum Difference Between Node and Ancestor

MediumTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop300AmazonMicrosoftGoogleAppleBloomberg

Given the root of a binary tree, return the maximum value of |a.val - d.val| over every pair (a, d) where a is an ancestor of d (a strict ancestor — a is not d itself). Equivalently, for every root-to-leaf path, look at every pair of nodes (a higher one and a lower one) and report the largest difference seen anywhere in the tree.

The brute force enumerates every (ancestor, descendant) pair in O(n²). The elegant observation is that the maximum |a.val - d.val| along any single root-to-leaf path is exactly max(path) - min(path) — that is, the largest value on the path minus the smallest value on the path. So instead of tracking all values, we only need to carry the minimum and maximum seen so far as we descend.

This becomes a clean preorder DFS where each call receives (node, minSoFar, maxSoFar). When we hit null we return maxSoFar - minSoFar — the best span achievable along this branch. At an internal node we update minSoFar = min(minSoFar, node.val) and maxSoFar = max(maxSoFar, node.val), then return the larger of the two child results.

The algorithm runs in O(n) time and O(h) space. Note that the problem guarantees the tree has at least 2 nodes, so the answer is always at least 0 and is always realized by an actual ancestor-descendant pair.

Examples

Example 1
Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: The path 8 → 3 → 6 → 7 has min 3 and max 8, giving a difference of 5. The path 8 → 10 → 14 has min 8 and max 14, giving a difference of 6. The path 8 → 3 → 1 has min 1 and max 8, giving a difference of 7 — the largest in the tree.
Example 2
Input: root = [1,null,2,null,0,3]
Output: 3
Explanation: The path 1 → 2 → 0 → 3 has min 0 and max 3, difference 3. No other path produces a larger span.
Example 3
Input: root = [2,4,1]
Output: 2
Explanation: Pairs (2,4) → |2-4|=2, (2,1) → |2-1|=1. The maximum is 2.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems