Maximum Difference Between Node and Ancestor

Given the `root` of a binary tree, find the maximum value `v` for which there exist different nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`. A node `a` is an ancestor of `b` if either any child of `a` is equal to `b`, or any child of `a` is an ancestor of `b`.

30:00

Maximum Difference Between Node and Ancestor
medium
Free written solution
Topics
Companies

Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.

A node a is an ancestor of b if either any child of a is equal to b, or any child of a is an ancestor of b.

Example 1:
Input: {"root":[8,3,10,1,6,null,14,null,null,4,7,13]}
Output: 7
Constraints:
  • The number of nodes in the tree is in the range [2,5000][2, 5000].

  • 0≤Node.val≤1050 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[8,3,10,1,6,null,14,null,null,4,7,13]}

For any node, the best partner among its ancestors is either the smallest or the largest value above it. So carry lo and hi down each path, starting at the root value 8.

831016144713

values on the current path, on a number line

114

lo

-

hi

-

returned

-

best

0

path

not started

current node
root-to-node path
lo (smallest on path)
hi (largest on path)
path with the widest span
Variables
VariableValue
nodenull
lo-
hi-
best0
DepthFunction Call
Stack empty
0/18