Skip to main content

How to Find the Minimum Distance Between Nodes in a Binary Search Tree (BST) – Optimized Solution Explained

 In a Binary Search Tree (BST), finding the minimum absolute difference between the values of any two distinct nodes is a classic problem in tree data structure algorithms. This problem is a natural extension of the concept of BST properties and is useful in scenarios such as range queries, nearest neighbor searches, and optimization problems.

In this blog post, we’ll walk through the approach to solve the problem of finding the minimum distance between two nodes in a BST. We will break down the solution, discuss different strategies, and demonstrate an optimized approach to solve the problem efficiently.


Problem Statement: Minimum Distance Between BST Nodes (LeetCode Problem 783)

Problem Description:

You are given the root of a Binary Search Tree (BST). Your task is to find the minimum absolute difference between the values of any two distinct nodes in the tree.

For example:

  • Input 1:

    root = [4, 2, 6, 1, 3] Output: 1

    The nodes with values 2 and 3 have the smallest absolute difference, which is 1.

  • Input 2:

    root = [1, 0, 48, null, null, 12, 49] Output: 1

    The nodes with values 0 and 1 have the smallest absolute difference, which is 1.


Exploiting the BST Property

The main insight here is to exploit the properties of the Binary Search Tree (BST). In a BST:

  • The left subtree contains values less than the current node's value.
  • The right subtree contains values greater than the current node's value.

This property ensures that an in-order traversal of the tree will yield values in sorted order. Since the nodes are sorted, the smallest absolute difference will always occur between adjacent nodes in the sorted order.

Thus, instead of comparing every pair of nodes, which would be inefficient, we can compute the minimum difference by performing an in-order traversal of the BST and checking the difference between each adjacent pair of nodes.


Approach and Solution Explanation

To solve the problem efficiently, we’ll use an in-order traversal to visit the nodes of the tree in sorted order. We keep track of the previous node’s value during the traversal. By comparing the current node's value with the previous node's value, we can compute the difference and keep track of the smallest difference encountered.

Solution Outline:

  1. In-order Traversal: This will ensure that the nodes are visited in increasing order of their values.
  2. Tracking the Minimum Difference: During the traversal, calculate the difference between each node and its predecessor.
  3. Edge Case Handling: If the tree is empty or has only one node, return an appropriate result (though the problem guarantees at least two nodes).

Code Implementation

Here’s the optimized code to solve the problem:

class Solution {
public:
    int mini = INT_MAX;  // Variable to store the minimum difference
    int pre = -1;        // Variable to store the value of the previous node during traversal

    void solve(TreeNode* root)
    {
        if (!root) return;  // Base case: if the root is null, return

        // Traverse the left subtree first (LNR order)
        solve(root->left);

        // Process the current node
        if (pre != -1)
        {
            mini = min(mini, root->val - pre);  // Calculate and update the minimum difference
        }
        pre = root->val;  // Update the previous node's value to the current node's value

        // Traverse the right subtree
        solve(root->right);
    }

    int minDiffInBST(TreeNode* root)
    {
        solve(root);  // Start the in-order traversal
        return mini;  // Return the minimum difference found
    }
};

Explanation of the Code:

  1. Base Case: If the current node (root) is NULL, we simply return without doing anything.
  2. In-order Traversal:
    • First, we recursively visit the left subtree (solve(root->left)).
    • We then process the current node. If this is not the first node (i.e., pre != -1), we compute the absolute difference between the current node's value and the previous node's value (pre). We update the mini variable to keep track of the smallest difference.
    • Finally, we update pre to the current node's value and recursively visit the right subtree (solve(root->right)).
  3. Return: After completing the in-order traversal, the mini variable will contain the minimum absolute difference between any two nodes in the BST, which we then return.

Time and Space Complexity:

  • Time Complexity: O(n), where n is the number of nodes in the BST. We visit each node exactly once during the in-order traversal.
  • Space Complexity: O(h), where h is the height of the tree. This is the space used by the recursion stack. In the worst case, for an unbalanced tree, the space complexity could be O(n), but in the best case (a balanced tree), it is O(log n).

Why This Solution is Efficient:

  1. Single Pass: The solution uses a single in-order traversal to visit each node exactly once. This ensures that we are working in O(n) time complexity, which is the best possible for this problem, as we must visit each node to calculate the minimum difference.

  2. No Extra Space: We only use a few integer variables (mini, pre) to keep track of the minimum difference and the previous node’s value. This makes the space complexity O(h), where h is the height of the tree, which is much more efficient than using extra data structures like arrays or lists.

In this blog post, we’ve walked through the problem of finding the minimum distance between nodes in a BST and discussed how to optimize the solution using an in-order traversal. The key insight is that by visiting the nodes in sorted order, the smallest differences will always be between adjacent nodes.

The optimized solution works in O(n) time and O(h) space, making it both time and space efficient. This approach is optimal for this problem and can be applied to other BST-related problems as well.

SEO Tags:

  • Minimum Distance Between BST Nodes
  • Leetcode 783 Solution
  • Binary Search Tree minimum difference
  • BST in-order traversal
  • Finding minimum difference in BST
  • Leetcode BST problems
  • Optimized BST search solution

Popular posts from this blog

LeetCode 2583: Kth Largest Sum in a Binary Tree – Solution Explained

When working with binary trees, one common task is to analyze the properties of the tree's levels. In this blog post, we'll walk through a solution to LeetCode Problem 2583: Kth Largest Sum in a Binary Tree , a problem that challenges us to compute and find specific sums from different levels of a binary tree. Problem Statement You are given the root of a binary tree and a positive integer k . Your goal is to return the k-th largest level sum in the tree. The level sum is defined as the sum of the values of all nodes at the same depth in the tree. If the number of levels in the tree is less than k , the function should return -1 . Example 1: Input: root = [5, 8, 9, 2, 1, 3, 7, 4, 6] , k = 2 Output: 13 Explanation: Level 1 sum: 5 Level 2 sum: 8 + 9 = 17 Level 3 sum: 2 + 1 + 3 + 7 = 13 Level 4 sum: 4 + 6 = 10 The 2nd largest sum is 13 . Example 2: Input: root = [1, 2, null, 3] , k = 1 Output: 3 Explanation: The largest level sum is 3 (at the third level). This problem essentia

BCA 5th and 6th Semester Project | BCSP-064 | Synopsys and Project | Both | IGNOU BCA | 100% Accepted | July 2023 and Jan 2024

 Synopsys and Project | Both | July 2023 and Jan 2024 Title of the Project : - PRODUCT HUB Buy it from here (Synopsis + Project) : Synopsis Content :- Synopsis : An overview of the entire project, summarizing its main objectives, scope, and outcomes. Introduction : Introduce the project and provide context for the reader by explaining the problem or need that the project aims to address. Aim and Objective : Clearly state the goals and objectives of the project, outlining what you intend to achieve through its completion. Project Category : Define the domain or category to which the project belongs, helping readers understand the context and purpose of the project. Tools and Platform : List the software tools, programming languages, and platforms you'll be using to develop and implement the project. System Analysis : Discuss the preliminary analysis phase of the project, where you identify requirements,

MCS-021 | Data and File Structures | IGNOU BCA Solved Assignment | July 2021 & January 2022

  Course Code :- MCS-021 Course Title :- Data and File Structures Assignment Number :- BCA(3)/021/Assignment/2021-22 Maximum Marks :-  100 Weightage :-   25% Last Dates for Submission :- 31st October, 2021 (For July Session) &  15th April, 2022 (For January Session)  This assignment has four questions which carry 80 marks. Answer all the questions. Each question carries 20 marks. You may use illustrations and diagrams to enhance the explanations. Please go through the guidelines regarding assignments given in the Programme Guide. All the implementations should be in C programming language. Question 1: Write an algorithm that accepts a Binary Tree as inputs and outputs the traversals of Inorder , Postorder and Preorder of it. Question 2: Is it possible to implement multiple queues in a Stack. Justify your answer.  Question 3: List the names of all Sorting Algorithms along with their Complexities (Best case, Average case and Worst case). List as many names as possible along