LeetCode 530: Minimum Absolute Difference in BST — Python Solution

LeetCode 530: Minimum Absolute Difference in BST is an Easy binary search tree problem. This Python walkthrough develops an inorder adjacent difference solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicBinary Search Tree
Reusable patterninorder adjacent difference
ComplexityO(n) time and O(h) recursion space

Recognizing the pattern

BST ordering turns inorder traversal into a sorted stream and lets inherited bounds rule out whole subtrees.

For this problem specifically, inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values. The invariant worth writing beside the code is: prev is the greatest value visited before the current node.

Step-by-step algorithm

  1. Identify the input state consumed by getMinimumDifference(root) and initialize the data required by the inorder adjacent difference pattern.
  2. Inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values.
  3. After each update, verify the page’s central invariant: prev is the greatest value visited before the current node.
  4. Finish only after the boundary behavior is covered: Initialize without a numeric sentinel so negative values are safe.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def getMinimumDifference(self, root):
        previous, best = None, float("inf")
        def inorder(node):
            nonlocal previous, best
            if not node: return
            inorder(node.left)
            if previous is not None: best = min(best, node.val - previous)
            previous = node.val
            inorder(node.right)
        inorder(root)
        return best

Reading the implementation

The main entry point is getMinimumDifference(root). The named working state includes previous; those variables make the inorder adjacent difference state visible instead of hiding it in incidental control flow.

The method expresses the transformation directly without a general traversal loop. In concrete terms, inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Inorder traversal visits BST values in sorted order, so the minimum absolute difference appears between adjacent visited values. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so prev is the greatest value visited before the current node.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Collecting all values and sorting works for a general tree, but it ignores the ordering guarantee and uses extra time or space. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

bst=tree([4,2,6,1,3]); assert Solution().getMinimumDifference(bst)==1 and s.Solution230().kthSmallest(bst,3)==3

Common mistakes and edge cases

  • Problem-specific boundary: Initialize without a numeric sentinel so negative values are safe.
  • Pattern-level pitfall: Use strict bounds when duplicates are invalid and avoid numeric sentinels that conflict with legitimate negative values.
  • Invariant check: after every update, confirm that prev is the greatest value visited before the current node.

Interview review checklist

  • Explain why inorder adjacent difference matches the structure of this input.
  • State the invariant in one sentence before tracing code: prev is the greatest value visited before the current node.
  • Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
  • Test the boundary explicitly: Initialize without a numeric sentinel so negative values are safe.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 103. Binary Tree Zigzag Level Order Traversal · Next: 230. Kth Smallest Element in a BST