Minimum Absolute Difference in Binary Search Tree (BST)

Difficulty: Medium, Asked-in: Google.

Key takeaway: An excellent problem to learn problem-solving using in-order traversal.

Let’s understand the problem!

Given the root of a binary search tree (BST), write a program to return the absolute minimum difference between the values of any two nodes in the tree.

  • The node values in the tree can be positive, negative, or zero.
  • Assume all node values in the tree are unique.

Examples

Input: 
          10 
        /   \ 
      -2     13 
      / \   / \ 
    -4   7 11  18

Output: 2
Explanation: Among all pair of nodes, the absolute difference 
between pair of nodes (-2, -4) and (13, 11) is 2, which is 
minimum. So we return 2 as an output.

Input:
          10 
        /   \ 
       5     13 
               \ 
               18
Output: 3
Explanation: Difference between pair of nodes (10, 13) is minimum. 

Discussed solution approaches

  • Using extra memory and recursive inorder traversal
  • In-place solution using recursive inorder traversal
  • Using iterative inorder traversal: stack-based approach

Using extra memory and recursive inorder traversal

Solution idea

We can use in-order traversal to traverse a binary search tree in sorted order. Suppose we store the values of the nodes in an extra array of size n. In that case, we can transform the problem into finding the absolute minimum difference in a sorted array.

In the sorted array, equal or closest values will appear next to each other. So the minimum difference must occur between adjacent elements. We only need to scan those (n - 1) adjacent pairs, calculate each difference, and keep track of the smallest one.

Solution pseudocode

inorder(root, sorted)
    if root is null
        return

    inorder(root.left, sorted)
    add root.data to sorted
    inorder(root.right, sorted)

minAbsoluteDifferenceBST(root)
    if root is null
        return INT_MAX

    sorted = empty list
    inorder(root, sorted)
    minDiff = INT_MAX
    for i from 1 to size(sorted) - 1
        difference = sorted[i] - sorted[i - 1]
        if difference < minDiff
            minDiff = difference

    return minDiff

Solution analysis

Time complexity = Time complexity of the in-order traversal + Time complexity of finding the minimum absolute difference in the sorted array = O(n) + O(n) = O(n).

Space complexity = Space complexity of using an extra array + Space complexity of the recursive in-order traversal = O(n) + O(h).

The space complexity of the recursive in-order traversal depends on the height of the tree. In the best case (when the tree is completely balanced), the height is O(logn), and in the worst case (when the tree is purely left-skewed or right-skewed), the height is O(n). So overall space complexity = O(n).

In-place solution using recursive inorder traversal

Solution idea

The critical questions are: Can we solve this problem in place or without using extra space? Can we track the absolute minimum difference using inorder traversal? Here are two insights:

  1. In-order traversal explores BST nodes in sorted order.
  2. In a sorted order, we need to compare the difference between adjacent values in order to find the minimum absolute difference.

To implement this, we maintain a variable to track the value of the previous node during in-order traversal. As we traverse the tree, we calculate the difference between the current node and the previous node. If this difference is smaller than the minimum difference so far, we can update the minimum difference.

Solution pseudocode

class Solution
    minDiff = INT_MAX
    previousValue = INT_MIN

    findMinimumDifference(root)
        if root is null
            return minDiff

        findMinimumDifference(root.left)
        // Compare the current value with the previous value
        if previousValue != INT_MIN
            minDiff = min(minDiff, root.data - previousValue)

        previousValue = root.data
        findMinimumDifference(root.right)

        return minDiff

Another implementation pseudocode

findMinimumDifference(root, prev, minDiff)
    if root is null
        return

    findMinimumDifference(root.left, prev, minDiff)
    if prev is not null
        minDiff = min(minDiff, root.data - prev.data)

    prev = root
    findMinimumDifference(root.right, prev, minDiff)

minimumDifferenceBST(root)
    prev = null
    minDiff = INT_MAX
    findMinimumDifference(root, prev, minDiff)
    return minDiff

Solution analysis

We are performing O(1) operation with each node. So time complexity = Time complexity of in-order traversal = O(n). Space complexity = Space complexity of recursive in-order traversal = O(h).

Using iterative inorder traversal

Solution idea

This approach is similar to the previous one, but it uses an iterative in-order traversal with the help of a stack instead of a recursive traversal. The basic idea is to pop the current node from the stack and compare the minimum difference found so far with the difference between the previous node and the current node. We update the minimum difference if this difference is smaller than the minimum difference.

Solution pseudocode

absMinDiffBST(root)
    minDiff = INT_MAX
    stack = empty stack
    current = root
    previous = null

    while stack is not empty or current is not null
        if current is not null
            push current onto stack
            current = current.left
        else
            current = top of stack
            pop stack

            if previous is not null
                minDiff = min(minDiff, current.data - previous.data)

            previous = current
            current = current.right

    return minDiff

Solution analysis

We are traversing each node only once and performing O(1) operation. So time complexity = Time complexity of in-order traversal = O(n). Space complexity = Space complexity of using stack = O(h). Think!

Critical ideas to think!

  • Can we use the above approaches to solve the problem if the tree is not a BST?
  • Can we solve the problem using other traversals?
  • Can we solve the problem using threaded binary tree traversal or Morris traversal?
  • Does the above solution work perfectly when values are repeated in the BST?

Comparison of time and space complexities

  • Inorder and extra space: Time = O(n), Space = O(n)
  • Inorder without extra space: Time = O(n), Space = O(h)
  • Iterative inorder using stack: Time = O(n), Space = O(h)

Suggested coding problems to practice

  • Recursive and iterative in-order traversal
  • K-diff Pairs in an Array
  • Find the minimum absolute difference in two different BST’s
  • Kth smallest element in a BST

Please write in the message below if you find anything incorrect, or you want to share more insight. Enjoy learning, Enjoy algorithms!

Visualization Lab

See how algorithmic problem solving approaches work and follow each step at your own pace.

Explore Visualisation Lab

Courses and Blogs