Minimum Distance between BST Nodes

Easy Topics Company Tags

Return the smallest absolute difference between the values of two different nodes in the binary search tree. This is a difference between node values, not the number of edges between nodes.

The tree follows the binary search tree rule: every value in a node's left subtree is smaller than its value, and every value in its right subtree is larger.

Examples use level-order arrays. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Minimum Distance Between BST Nodes, example 1: illustration of the example

Input: root = [10,4,20,1,7,15,30]

Output: 3

Explanation: The sorted values are [1,4,7,10,15,20,30]. The smallest gap is 3, achieved by several pairs, including 1 and 4.

Example 2:

Minimum Distance Between BST Nodes, example 2: illustration of the example

Input: root = [20,5,40,null,18]

Output: 2

Explanation: The values 18 and 20 differ by 2. No other pair is closer; these nodes need not be directly connected by an edge.

Example 3:

Minimum Distance Between BST Nodes, example 3: illustration of the example

Input: root = [0,null,100000]

Output: 100000

Explanation: There are only two nodes, with values 0 and 100000. Their absolute difference is 100000.

Constraints:

  • The tree contains between 2 and 100 nodes.
  • 0 <= Node.val <= 100000
  • The input is a binary search tree with distinct node values.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.