DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

530. Minimum Absolute Difference in BST

🧠 Approach: Inorder Traversal (Sorted View of BST)

In a BST, an inorder traversal gives us a sorted sequence of values.

So instead of comparing every pair of nodes (which would be O(n²)), we can:

  1. Do an inorder traversal.
  2. At each step, compare the current node’s value with the previous node’s value.
  3. Keep track of the minimum absolute difference.

Why this works:

In a sorted list, the smallest difference must be between two consecutive values.


✅ Code (JavaScript):

var getMinimumDifference = function (root) {
  let prev = null;
  let minimum = Infinity;

  function inorder(node) {
    if (!node) return;

    inorder(node.left);

    if (prev !== null) {
      minimum = Math.min(minimum, Math.abs(node.val - prev.val));
    }

    prev = node;

    inorder(node.right);
  }

  inorder(root);
  return minimum;
};
Enter fullscreen mode Exit fullscreen mode

📦 Example:

For a tree like:

     4
    / \
   2   6
  / \
 1   3
Enter fullscreen mode Exit fullscreen mode

Inorder traversal: [1, 2, 3, 4, 6]

Minimum difference = min(1, 1, 1, 2) = 1


⏱ Time & Space Complexity

Type Complexity
Time O(n) — Every node visited once
Space O(h) — Due to recursion stack (h = height of tree)

Top comments (0)