Tensorum
LeetCode 530 · Tree

Minimum Absolute Difference in BST

LeetCode 530 · Easy · solution, intuition & step-by-step walkthrough

In-order with a previous-node pointer.

EasyTreeDepth-First SearchBreadth-First SearchBinary Search TreeBinary Tree
0 msruntime · beats 100%
54.8 MBmemory · beats 100%
1approach
2accepted runs · last 15 Dec 2024

This is how I solved Minimum Absolute Difference in BST (LeetCode 530), an easy problem from the Tree pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

In-order traversal of a BST visits values in sorted order, and the smallest difference in a sorted list is always between neighbours. Remember the previous node visited and compare.

Approach

  1. 1

    In-order DFS.

  2. 2

    If there is a previous node, update min with the gap.

  3. 3

    Set previous to the current node.

How I solved it

In-order with prevPythonO(n) time · O(h) space
class Solution:
    def getMinimumDifference(self, root):
        self.prevNode = None
        self.mn = float("inf")

        def dfs(node):
            if node is None:
                return
            dfs(node.left)
            if self.prevNode is not None:
                self.mn = min(self.mn, abs(node.val - self.prevNode.val))
            self.prevNode = node
            dfs(node.right)
        dfs(root)
        return self.mn
Loading the step-through…

Minimum Absolute Difference in BST — FAQ

What is the intuition behind Minimum Absolute Difference in BST?

In-order traversal of a BST visits values in sorted order, and the smallest difference in a sorted list is always between neighbours. Remember the previous node visited and compare.

How do you solve Minimum Absolute Difference in BST (LeetCode 530)?

1. In-order DFS. 2. If there is a previous node, update min with the gap. 3. Set previous to the current node.

What is the time and space complexity of Minimum Absolute Difference in BST?

Time: O(n). Space: O(h). (Accepted approach: In-order with prev.)

What are common mistakes in Minimum Absolute Difference in BST?

Comparing a node only with its children misses neighbours across subtrees.