Problem 420
Maximum Difference Between Node and Ancestor
Medium · 20 pts · Tree, Depth-First Search, Binary Tree
Problem
Node A is an ancestor of node B if B lies somewhere in A's subtree (A is B's parent, grandparent, and so on). Find the largest value of |A.value - B.value| over all pairs where A is an ancestor of B. Instead of comparing every pair, carry the minimum and maximum values seen on the path from the root down to each node; the best difference at a node uses those extremes.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the maximum difference.
Constraints
2 <= number of nodes <= 5000; 0 <= value <= 100000
Example input
12 8 3 10 1 6 null 14 null null 4 7 13
Example output
7
Explanation
In the tree 8 / 3 10 / 1 6 _ 14 / _ _ 4 7 13, the node 8 is an ancestor of 1, and |8 - 1| = 7 is the largest such difference.