AlgoMaster Logo

Minimum Distance Between BST Nodes

Last Updated: November 19, 2025

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with Inorder Traversal

Intuition:

A binary search tree (BST) has the property that for any node, the value of all the nodes in its left subtree are less and all the nodes in its right subtree are greater. Thus, an inorder traversal of a BST will yield the nodes in sorted order.

The brute force approach is to perform an inorder traversal of the BST to obtain a sorted list of node values. We then compute the minimum difference between consecutive values in this sorted list.

Steps:

  1. Perform an inorder traversal to extract values in sorted order.
  2. Calculate the minimum difference between consecutive elements in this sorted list.

Code:

2. Optimized Inorder Traversal

Intuition:

We can optimize the space usage by calculating the minimum difference on-the-fly during the inorder traversal, rather than maintaining a list of values. This way, we only need to keep track of the last visited node's value.

Steps:

  1. Perform an inorder traversal.
  2. During traversal, calculate the difference between the current node value and the previous node value (i.e., last node visited in inorder traversal).
  3. Update the minimum difference accordingly.

Code:

3. Iterative Inorder Traversal

Intuition:

Instead of storing all node values, we can compute the minimum difference on the fly during inorder traversal. Since inorder gives nodes in sorted order, we only need to compare each node with the previously visited one.

Steps:

  • Perform an inorder traversal.
  • Keep track of the value of the previously visited node.
  • For each visited node, compute the difference between its value and the previous value.
  • Update the minimum difference whenever a smaller gap is found.