Minimum Absolute Difference in BST

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

30:00

Minimum Absolute Difference in BST
easy
Free written solution
Topics
Companies

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Example 1:
Input: {"root":[4,2,6,1,3]}
Output: 1
Constraints:
  • The number of nodes in the tree is in the range [2,104][2, 10^4].

  • 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":[4,2,6,1,3]}

prev starts empty and best at infinity. An inorder walk of a BST meets the values in sorted order, so only neighbours in that order need comparing.

42613inorder = sorted order

open calls

none

prev = None best = inf

current node / gap
open inorder calls
visited, in sorted order
smallest gap so far
Variables
VariableValue
nodenull
prevNone
bestinf
DepthFunction Call
Stack empty
0/16