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|abababab
Example 1
Output: 7
Explanation: 8 is an ancestor of 1, and |8 - 1| = 7.
Example 2
Output: 3
Explanation: 0 is an ancestor of 3, and |0 - 3| = 3.
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
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 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 lohidfs(node, lo, hi)node.val
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
Measuring the gap where a path ends
When does a path end? When dfsnullhi - lo
A node with one child, such as 10 in Example 1, also has a nullnulllohinull
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
- First, start the walk with
, sodfs(root, root.val, root.val) andlo both begin at the root's value.hi - In
, ifdfs isnode , a path has ended: returnnull .hi - lo - Otherwise, take the current node into the pair:
becomeslo andMath.min(lo, node.val) becomeshi .Math.max(hi, node.val) - Call
ondfs and onnode.left with the newnode.right andlo , and return the larger of the two results.hi
Around the method, a small TreeNodebuildrun
The main
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:
[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][4, 4, 4, 4]lohi
Look at the fifth line, [5, 9, 1, 7, null, null, 4, 2] -> 7lohi
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
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.dfs - 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