Maximum Difference Between Node and Ancestor

MediumTrees · DFS (Carry Path Min/Max)🧩 Tree DFSLeetCode #1026 ↗Updated

Problem

Given the root of a binary tree, consider every pair of different nodes a and b where a is an ancestor of b (it lies on the path from the root down to b). Return the largest possible value of |a.val − b.val|.
Inputroot = [5,9,2,null,null,0,7]Output5
Inputroot = [1,null,2,null,0,3]Output3
Inputroot = [4,4]Output0

2 ≤ nodes ≤ 5000  ·  0 ≤ Node.val ≤ 105

Try it yourself

Java
class Solution {
    public int maxAncestorDiff(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
For a fixed node, the best ancestor partner is either the smallest or the largest value above it. So carry just the running min and max of the current root-to-node path; at a leaf, max − min is the best difference on that path.
PatternTree DFS

Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.

Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.

Open the Tree DFS guide →

Approaches

Brute ForceEach Node vs. Its Whole Subtree

Time O(n · h)Space O(h)

Treat every node as the ancestor in turn and scan all its descendants, tracking the largest |ancestor − descendant|. Every valid pair is examined, so the maximum is exact.

Java
public int maxAncestorDiff(TreeNode root) {
    if (root == null) return 0;
    int best = Math.max(farthest(root.left, root.val), farthest(root.right, root.val));
    best = Math.max(best, maxAncestorDiff(root.left));
    return Math.max(best, maxAncestorDiff(root.right));
}
// Largest |x.val - val| over every node x in this subtree.
private int farthest(TreeNode node, int val) {
    if (node == null) return 0;
    int here = Math.abs(node.val - val);
    return Math.max(here, Math.max(farthest(node.left, val), farthest(node.right, val)));
}

Correct by exhaustion, but a skewed tree (h = n) makes it O(n²).

At a glance

LevelApproachTimeSpace
Brute ForceEach Node vs. Its Whole SubtreeO(n · h)O(h)
BetterBottom-up Subtree Min/MaxO(n)O(h)
OptimalTop-down Path Min/MaxO(n)O(h)
Common pitfalls
  • Comparing only parent and child — the best pair can be many levels apart.
  • Tracking just the path max (or just the min); you need both to cover |a − b|.
  • Updating a global min/max instead of per-path values leaks state between sibling branches.
Interview tips
  • Reduce the problem: for each node only the extreme ancestors matter.
  • Point out that pairs on one root-to-leaf path are exactly the ancestor pairs.
  • Mention both directions (top-down vs bottom-up) and pick the simpler one.
Pattern
Top-down DFS carrying path state → when a node's answer depends on aggregates (min, max, sum) of its ancestors.
My notes saved in this browser