Maximum Difference Between Node and Ancestor

Find the widest gap between a node's value and the value of any node above it in a binary tree.

Given the root of a binary tree with at least two nodes, return the largest difference |a.val - b.val| over all pairs of nodes a and b where a is an ancestor of b. A node a is an ancestor of b when a lies on the way from the root down to b: its parent, its parent's parent, and so on up to the root.

Example 1
Input: root = [8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]
Output: 7
Explanation: 8 is an ancestor of 1, and |8 - 1| = 7.
Example 2
Input: root = [1, null, 2, null, 0, 3]
Output: 3
Explanation: 0 is an ancestor of 3, and |0 - 3| = 3.
Solution

The Idea

Picture your own family line. Your parent is above you, and so are your grandparents and great-grandparents, all the way to the oldest person at the top. Each of them is your ancestor. Here every person is a number, and we want a person and one of their ancestors whose numbers are furthest apart.

The input lists the tree row by row, with null where a child is missing. In Example 1, the top node, the root, is 8. Its children are 3 and 10. Below 3 come 1 and 6, and below 10 only a right child, 14. The last row holds 4 and 7 under 6, and 13 under 14.

Could each node just be compared with its parent? Not quite. The biggest gap between a parent and its child in Example 1 is 8 - 3 = 5. Yet 8 is also an ancestor of 1, two levels down, and they differ by 7, the answer. So which of a node's ancestors should it be compared with?

Among a group of numbers, the one furthest from a given number is always the smallest or the largest of the group. So a node needs only two facts about the nodes above it: their smallest value and their largest value. Look at the picture below. Beside each node it shows the smallest and largest value on the path from the root down to that node: the root, the node itself and every node between them.

The tree of Example 1. Beside each node is the smallest and largest value on the path from the root down to it. At the nodes with no children the gaps are 7 for 1, 5 for 4 and 7, and 6 for 13. The path 8, 3, 1 is highlighted.

The root shows [8, 8], since 8 is the only value so far. Going down to 3 makes it [3, 8], and going on to 1 makes it [1, 8]. Node 1 has no children, so its path ends there, and the gap shown under it is 8 - 1 = 7. The other paths end at 4 and 7 with a gap of 5, and at 13 with a gap of 6.

Why is the gap of a whole path enough? The smallest and largest values on one path always belong to two nodes on that path, and the one nearer the root is an ancestor of the other. Also, any node and its ancestor sit together on some path from the root down. So the answer is the biggest gap over all paths, which is 7, on the highlighted path 8, 3, 1.

Solution Approach

Turning that idea into code means deciding what each node hands to its children, where a path's gap is measured, and how the gaps of all paths are combined. The slow way, comparing every node with each of its ancestors, comes first, to show what the idea saves.

Comparing every node with each ancestor

What happens if each node simply walks up to the root and compares itself with every node on the way? That works, but a tree shaped like one long chain, where each node has a single child, makes it slow. With n nodes, the last node compares with n - 1 others, the one above it with n - 2, and so on: about n²/2 comparisons in all.

What each node hands to its children

Which facts must travel down the tree? Only two numbers, the smallest and largest values on the path so far, held in variables named lo and hi. A method dfs(node, lo, hi) takes them, updates them with node.val, and calls itself on the left child and on the right child with the new pair. Both numbers start at the root's value.

The method goes all the way down the left side of a node before it starts on the right side. Walking a tree in this order is called depth-first search, which is where the name dfs comes from.

Measuring the gap where a path ends

When does a path end? When dfs is called on a missing child, a null. At that point hi - lo is the biggest gap on the path just walked, so the call returns it. No node is compared with anything on its own.

A node with one child, such as 10 in Example 1, also has a null on its other side. The call on that null returns the gap of the shorter path 8, 10, which is 2. It can never be bigger than the gap of the longer path 8, 10, 14, 13, because going further down only widens lo and hi. So the extra null does no harm.

Combining the paths

How does one answer come out of all the paths? Each call returns the larger of what its left and right calls returned. Results travel back up the tree that way, and the call on the root returns the biggest gap of any path.

Java Solution

The method maxAncestorDiff works in these steps:

  1. First, start the walk with dfs(root, root.val, root.val), so lo and hi both begin at the root's value.
  2. In dfs, if node is null, a path has ended: return hi - lo.
  3. Otherwise, take the current node into the pair: lo becomes Math.min(lo, node.val) and hi becomes Math.max(hi, node.val).
  4. Call dfs on node.left and on node.right with the new lo and hi, and return the larger of the two results.

Around the method, a small TreeNode class holds a value and links to a left and a right child. The helper build turns the row-by-row array into a tree, and run prints the array with its answer.

The main method runs both examples, a tree of two nodes, a tree whose values are all equal, a tree whose best pair leaves out the root, and a chain of five nodes.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class MaximumDifferenceBetweenNodeAndAncestor {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public static int maxAncestorDiff(TreeNode root) {
        return dfs(root, root.val, root.val);
    }

    // lo and hi: the smallest and largest values on the path from the root down to node
    private static int dfs(TreeNode node, int lo, int hi) {
        if (node == null) {
            return hi - lo;                   // the path ended: its widest gap
        }
        lo = Math.min(lo, node.val);
        hi = Math.max(hi, node.val);
        return Math.max(dfs(node.left, lo, hi), dfs(node.right, lo, hi));
    }

    // builds a tree from the row-by-row form, with null for a missing child
    static TreeNode build(Integer[] values) {
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    static void run(Integer... values) {
        System.out.println(Arrays.toString(values) + " -> " + maxAncestorDiff(build(values)));
    }

    public static void main(String[] args) {
        run(8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13);
        run(1, null, 2, null, 0, 3);
        run(5, 2);
        run(4, 4, 4, 4);
        run(5, 9, 1, 7, null, null, 4, 2);
        run(1, null, 2, null, 3, null, 4, null, 5);
    }
}

Running it prints:

Output
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13] -> 7
[1, null, 2, null, 0, 3] -> 3
[5, 2] -> 3
[4, 4, 4, 4] -> 0
[5, 9, 1, 7, null, null, 4, 2] -> 7
[1, null, 2, null, 3, null, 4, null, 5] -> 4

Example 1 gives 7, from 8 and 1, and Example 2 gives 3, from 0 and the 3 below it. With only [5, 2], the root's 5 and its child's 2 give 3. In [4, 4, 4, 4] every path has lo and hi both at 4, so the answer is 0.

Look at the fifth line, [5, 9, 1, 7, null, null, 4, 2] -> 7. The root 5 has children 9 and 1, with 7 and then 2 below 9, and 4 below 1. The path 5, 9, 7, 2 has a gap of 7, and it comes from 9 and 2, two levels apart, with the root not involved. The other path, 5, 1, 4, only reaches 5 - 1 = 4. The last line is a chain 1 to 5, where lo stays at 1 while hi grows to 5.

Complexity

The walk visits each node once and keeps only two numbers per call, so the cost follows the size and the height of the tree.

  • Time: O(n), because dfs runs once for each of the n nodes and once for each missing child below them, and each call does a fixed amount of work.
  • Space: O(h), because only the calls along the current path from the root wait at any moment, and h, the number of nodes on the longest path from the root, limits that path. A chain of n nodes makes h equal to n.

Carrying a value down the tree as a parameter also solves Path Sum, which passes the running sum of the path instead.