File: minimum-distance-between-bst-nodes/solution.py

Date: 2026-06-06

Time: 17:57

minimum-distance-between-bst-nodes/solution.py

Purpose

Solves LeetCode 783 — Minimum Distance Between BST Nodes. Given a BST, find the minimum absolute difference between the values of any two nodes. This file owns the solution, the tree construction helper, and the test suite — a self-contained unit typical of this repo's per-problem structure.

Key Components

TreeNode — Standard binary tree node with val, left, right. Used both by the solution and the test harness.

Solution.minDiffInBST(root) — The core algorithm. Uses an in-order traversal to visit nodes in sorted order, tracking the previous value via self.prev and updating self.mindiff with the smallest gap seen. Returns self.mindiff (an int for valid BSTs, initialized to float('inf')).

build_tree(vals) — Constructs a TreeNode tree from a level-order list (LeetCode's standard serialization format). None entries represent absent children. Used exclusively by tests.

TestSolution — Six test cases covering both LeetCode examples, two-node trees, large gaps, consecutive values, and right-skewed trees.

Patterns

In-order traversal on BST yields sorted order. This is the central insight. Rather than collecting all values into a list and sorting, the solution streams through sorted values and computes adjacent differences on the fly — O(n) time, O(h) stack space.

Instance variables as closure state. self.prev and self.min_diff are set on self before traversal starts, then mutated by the nested inorder function. This avoids passing accumulators through recursive calls or using nonlocal. It does mean the Solution instance is stateful during execution — calling minDiffInBST resets both fields at the top, so it's safe to reuse across calls.

Level-order deserialization. build_tree uses a queue (list with pop(0)) to assign children left-to-right, matching LeetCode's bracket notation.

Dependencies

Imports: Optional from typing (for the type hint), unittest (test framework). No external dependencies.

Imported by: The test file minimum-distance-between-bst-nodes/test_solution.py imports from this module. The massive "Imported By" list in the prompt is an artifact of the repo's structure — those are unrelated test files that share the same import pattern, not actual consumers of this solution.

Flow

1. minDiffInBST initializes self.prev = None, self.min_diff = inf.

2. inorder(node) recurses left, processes current node, recurses right.

3. On each node visit: if self.prev is not None, compute node.val - self.prev (guaranteed non-negative because BST in-order is sorted ascending) and update self.min_diff if smaller.

4. Set self.prev = node.val so the next visited node can compare against it.

5. After traversal completes, return self.min_diff.

Invariants

Error Handling

None. The function trusts its input is a valid BST with at least two nodes per the problem constraints. No exceptions are raised or caught. build_tree will silently produce a malformed tree if the input list is inconsistent.