Problem 783

Abstract / Summary

Find the smallest difference between values of any two nodes in a binary search tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0783.py

class Solution:
    def minDiffInBST(self, root: Optional[TreeNode]) -> int:
        all = []
        def deeper(node):
            if node:
                all.append(node.val)
                deeper(node.left)
                deeper(node.right)

        deeper(root)

        all.sort()
        best = all[1] - all[0]
        for i in range(2, len(all)):
            best = min(best, all[i] - all[i - 1])
        return best
16 lines | 443 bytes | submitted October 6, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (400k+ submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the smallest absolute difference between the values of any two nodes in a binary search tree (BST). It follows a three-phase approach: a depth-first traversal that gathers every node value, a sorting step that orders the collected values, and a linear scan that determines the minimal adjacent difference. The algorithm leverages Python’s built-in list handling and sorting facilities to keep the code concise.

Traversal and Collection

The first phase defines a nested helper function that recursively visits each node. The helper checks whether the current node exists, appends its value to a list, and then recurses on the left and right children. This depth-first strategy ensures that every node in the tree contributes its value to the collection, regardless of the tree’s shape-whether it is balanced, left-heavy, right-heavy, or completely linear.

all = []
def deeper(node):
    if node:
        all.append(node.val)
        deeper(node.left)
        deeper(node.right)

Calling deeper(root) initiates the traversal from the root of the BST, populating the list all with all node values.

Sorting the Values

After the traversal finishes, the list all contains an unsorted snapshot of the tree’s values. The code then invokes the list’s sort method, which rearranges the elements in non-decreasing order. By relying on Python’s highly optimized Timsort algorithm, the implementation benefits from adaptive performance characteristics that handle already partially ordered data efficiently.

all.sort()

The sorted order is crucial because the minimal difference between any two values in a set must occur between two consecutive elements when the set is ordered.

Computing the Minimum Difference

With the values sorted, the algorithm initializes the best (minimum) difference using the first two elements. It then iterates from the third element to the end of the list, updating the best value whenever a smaller gap between the current element and its immediate predecessor is found. This single pass guarantees that the smallest possible difference is identified without the need for nested comparisons.

best = all[1] - all[0]
for i in range(2, len(all)):
    best = min(best, all[i] - all[i - 1])
return best

Edge Cases Handled

The code gracefully accommodates trees that are highly unbalanced, such as those that degenerate into a linked list. Because the traversal visits nodes recursively without assuming any particular balance, every node is still recorded. The sorting step correctly orders values even when the BST contains duplicate entries; in that scenario, the adjacent difference becomes zero, which the subsequent scan captures as the minimal possible result. The linear scan also works correctly for the smallest permissible tree size (two nodes), where the initial best assignment directly yields the answer.

Performance Optimizations Observed

The implementation makes effective use of Python’s built-in data structures. The list all grows dynamically as values are appended, avoiding the overhead of manual resizing. The recursive traversal is tail-recursive in spirit, though Python does not optimize tail calls; nevertheless, the call stack depth matches the tree height, which is acceptable for typical BST sizes. The choice of Timsort for sorting provides a fast, stable sort that adapts to existing order, reducing work for partially sorted inputs that can arise from certain tree configurations. Finally, the post-sort linear scan computes the minimum difference in a single pass, eliminating any redundant comparisons that a naïve double-loop approach would incur.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big family tree made of squares that each have a secret number written on them. To find the smallest gap between any two numbers, the computer first goes on a treasure hunt to find all the numbers hidden in every part of the tree. It keeps dropping these numbers into a single basket until every single one is collected. Once the basket is full of numbers, the computer sorts them from the smallest to the biggest, just like lining up toys from shortest to tallest. After they are in order, the computer looks at the neighbors side by side and measures the distance between them. It keeps track of the tiniest distance it finds while walking down the line of numbers. By the time it finishes checking every pair of neighbors, the smallest gap is tucked away as the final answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.89 | σ = 1.20

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java JS Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
36 links | 22 authors | 9 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 3 medium
5 solutions   October 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality