Minimum Absolute Difference in BST

EASY

Description

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • The number of nodes in the tree is in the range [2, 104].
  • 0 <= Node.val <= 105

 

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/


Approaches

Checkout 3 different approaches to solve Minimum Absolute Difference in BST. Click on different approaches to view the approach and algorithm in detail.

Traversal and Sorting

A more optimized approach is to collect all node values, sort them, and then find the minimum difference between adjacent elements. The minimum difference in a sorted set of numbers will always occur between two consecutive numbers.

Algorithm

  • Create an empty list values.
  • Traverse the tree (e.g., using pre-order traversal) and add all node values to the values list.
  • Sort the values list using Collections.sort().
  • Initialize minDiff to Integer.MAX_VALUE.
  • Iterate through the sorted list from the second element (i = 1 to values.size() - 1).
  • In each iteration, calculate the difference: diff = values.get(i) - values.get(i - 1).
  • Update minDiff = Math.min(minDiff, diff).
  • Return minDiff.

Similar to the brute-force approach, we first traverse the tree to collect all node values into a list. Any traversal order (pre-order, in-order, or post-order) works for this step. Once we have the list of all values, we sort it in ascending order. After sorting, the problem is reduced to finding the minimum difference between any two adjacent elements in the sorted list. We iterate through the sorted list from the second element and calculate the difference between the current element and the previous one. We keep track of the minimum difference found during this single pass.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int getMinimumDifference(TreeNode root) {
        List<Integer> values = new ArrayList<>();
        collectValues(root, values);
        
        Collections.sort(values);
        
        int minDiff = Integer.MAX_VALUE;
        for (int i = 1; i < values.size(); i++) {
            minDiff = Math.min(minDiff, values.get(i) - values.get(i - 1));
        }
        return minDiff;
    }

    private void collectValues(TreeNode node, List<Integer> values) {
        if (node == null) {
            return;
        }
        values.add(node.val);
        collectValues(node.left, values);
        collectValues(node.right, values);
    }
}

Complexity Analysis

Time Complexity: O(N log N), where N is the number of nodes. The tree traversal takes O(N), sorting the list takes O(N log N), and the final pass takes O(N). The sorting step is the bottleneck.Space Complexity: O(N) to store the node values in a list. The recursion stack for traversal also contributes up to O(N) in the worst case.

Pros and Cons

Pros:
  • Significantly more efficient than the brute-force approach.
  • Relatively easy to implement.
Cons:
  • Still not optimal as it requires extra space for the list and an O(N log N) sorting step.
  • It doesn't fully exploit the BST property in real-time; it uses it indirectly by sorting the collected values.

Code Solutions

Checking out 4 solutions in different languages for Minimum Absolute Difference in BST. Click on different languages to view the code.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int ans ; private int prev ; private int inf = Integer . MAX_VALUE ; public int getMinimumDifference ( TreeNode root ) { ans = inf ; prev = inf ; dfs ( root ); return ans ; } private void dfs ( TreeNode root ) { if ( root == null ) { return ; } dfs ( root . left ); ans = Math . min ( ans , Math . abs ( root . val - prev )); prev = root . val ; dfs ( root . right ); } }

Video Solution

Watch the video walkthrough for Minimum Absolute Difference in BST



Algorithms:

Depth-First SearchBreadth-First Search

Data Structures:

TreeBinary TreeBinary Search Tree

Subscribe to Scale Engineer newsletter

Learn about System Design, Software Engineering, and interview experiences every week.

No spam, unsubscribe at any time.