Ctrl K

Widest Gap to an Ancestor

Medium
You are given the root of a binary tree whose nodes hold non-negative numbers. A node a is an ancestor of a node b when b lies in the subtree of a and is not a itself: a child of a, a child of that child, and so on down. Among all ancestor-descendant pairs, find the one whose values differ the most and return the absolute value of that difference.
Example 1
root=tree_node([5, 9, 2, 12, None, None, 0]) → 7

Node 12 sits below 9 and 5, node 0 sits below 2 and 5. The best pairs are |12 − 5| = 7 and |0 − 5| = 5, so the answer is 7; 12 and 0 are in different branches and do not count.

Example 2
root=tree_node([4, None, 4, None, 4]) → 0

Every value on the chain is the same, so every gap is 0.

Example 3
root=tree_node([3, 1, 8, None, None, 6, 20]) → 17

The pair of the root 3 and its descendant 20 gives 17, more than |8 − 20| = 12 or |3 − 1| = 2.

Constraints
  • 2 ≤ number of nodes ≤ 10⁵
  • 0 ≤ Node.val ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([5, 9, 2, 12, None, None, 0])
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 90 tests on the server, hidden ones included.