AlgoMaster Logo

Minimum Distance Between BST Nodes

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: