Problem 530

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 0530.py

class Solution:
    def getMinimumDifference(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()
        all.append(float("inf"))

        result = float("inf")
        for i in range(len(all) - 1):
            result = min(result, all[i + 1] - all[i])

        return result
19 lines | 495 bytes | submitted August 31, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (1+ million 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 values of any two nodes in a binary tree. It follows a straightforward three-phase approach: collect all node values, sort them, and then scan the sorted sequence to find the minimal gap. The algorithm leverages Python’s built-in list handling and sorting facilities, which contributes to its overall efficiency.

Key Steps

Traversal and Collection

The inner function performs a depth-first traversal, visiting each node exactly once and appending its value to a list named 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 tree, guaranteeing that every reachable node contributes its value to the collection.

Sorting

After the traversal completes, the list all contains an unsorted collection of node values. The code then sorts the list in ascending order using Python’s highly optimized Timsort algorithm.

all.sort()

Sentinel Insertion

To simplify the subsequent scan for differences, a sentinel value representing positive infinity is appended to the end of the sorted list. This guarantees that the loop can safely access all[i + 1] without additional boundary checks.

all.append(float("inf"))

Minimum Difference Scan

The final phase iterates over the sorted list, comparing each element with its immediate successor. The variable result holds the smallest difference encountered so far, and it is updated using the built-in min function.

result = float("inf")
for i in range(len(all) - 1):
    result = min(result, all[i + 1] - all[i])

When the loop finishes, result contains the minimum absolute difference between any two node values, which the function returns.

return result

Edge Cases Handled

When the input tree is empty, the traversal yields an empty list. After sorting and appending the sentinel, the loop runs zero times, leaving result as positive infinity, which is then returned. This behavior gracefully indicates that no pair of values exists to compute a difference.

For a tree consisting of a single node, the list contains exactly one value. The sentinel ensures that the loop executes once, computing the difference between the node’s value and infinity, which again results in result remaining infinity. This correctly reflects the absence of a second value to compare.

The use of the sentinel also protects against out-of-range indexing when the list contains only one element, as the loop’s range calculation (len(all) - 1) yields zero, preventing any invalid access.

Performance Optimizations

The algorithm benefits from several implicit optimizations. The depth-first traversal builds the list in place, avoiding the overhead of creating intermediate structures. Python’s native list append operation runs in amortized constant time, ensuring that the collection phase scales linearly with the number of nodes.

Sorting leverages Timsort, which adapts to existing order in the data and provides excellent performance on partially sorted inputs. By sorting once and then performing a single linear scan, the code minimizes the number of passes over the data.

Appending a sentinel value eliminates the need for explicit boundary checks inside the loop, allowing the inner computation to remain a simple arithmetic operation and a single call to min. This reduces branch mispredictions and keeps the hot loop tight.

Overall, the combination of in-place data structures, a single sort, and a boundary-free scan yields an implementation that is both concise and performant for the problem at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big treasure map shaped like a branching tree, where every branch has a numbered box hanging from it. This code is like a little robot helper designed to visit every single branch to find the numbers inside.

First, the robot starts at the very top of the tree, which is called the root. It wanders down every path, picking up the number from each box it finds and putting them all into a big toy chest tray. The robot keeps looking until there are no more paths left to explore.

Once the robot has all those numbers together in the toy chest, it neatly lines them up from the smallest number to the biggest number. This makes it much easier to see which numbers are close buddies and which ones are far apart.

Next, the robot looks at the line of numbers and checks the neighbors. It finds the difference between the first number and the second number, then the second and the third, and so on. It remembers the smallest difference it sees during this hunt. It keeps track of the tiniest gap it discovers between any two neighbors in that line. By the time it finishes checking every pair in the tray, it knows exactly how close the two closest numbers are to each other.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.19 | σ = 1.04

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 Python JS Rust Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
40 links | 25 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Minimum Absolute Difference in BST - Leetcode 530 - Trees (Python)'
Greg Hogg 7 mins
Minimum Absolute Difference in BST - Leetcode 530 - Trees (Python)
YouTube video 'Minimum Absolute Difference in BST | Leetcode - 530'
Algorithms Made Easy 15 mins
Minimum Absolute Difference in BST | Leetcode - 530
YouTube video 'Minimum Absolute Difference in BST | LEETCODE - 530 | Easy solution'
hi-malik 9 mins
Minimum Absolute Difference in BST | LEETCODE - 530 | Easy solution
YouTube video 'Leetcode 530 | Minimum Absolute Difference in BST'
INT_MAX 12 mins
Leetcode 530 | Minimum Absolute Difference in BST
YouTube video '530. Minimum Absolute Difference in BST | English | Easy'
Simple Code - 단순코드 6 mins
530. Minimum Absolute Difference in BST | English | Easy
YouTube video 'Leetcode #530: Minimum Absolute Difference in BST C++ Solution'
Zakaria Ridouh 7 mins
Leetcode #530: Minimum Absolute Difference in BST C++ Solution
YouTube video '530. Minimum Absolute Difference in BST | Inorder Traversal | BFS | LeetCode Daily Challenge'
Deep Tech 12 mins
530. Minimum Absolute Difference in BST | Inorder Traversal | BFS | LeetCode Daily Challenge
YouTube video 'Minimum Absolute Difference in BST - LeetCode 530 - Python'
Alpha-Code 14 mins
Minimum Absolute Difference in BST - LeetCode 530 - Python
YouTube video 'LeetCode 530 | Minimum Absolute Difference in BST | InOrder Traversal | Java'
Sleepy Cracker 6 mins
LeetCode 530 | Minimum Absolute Difference in BST | InOrder Traversal | Java
YouTube video 'Minimum Absolute Difference in BST - Leetcode 530 - Python (Recursive And Iterative Approach)'
TechError 14 mins
Minimum Absolute Difference in BST - Leetcode 530 - Python (Recursive And Iterative Approach)
YouTube video 'Leetcode-530 : Minimum Absolute Difference in BST (Leetcode 783)'
Kumar Sanjeev 5 mins
Leetcode-530 : Minimum Absolute Difference in BST (Leetcode 783)
YouTube video 'Minimum Absolute Difference in BST - Leetcode 530 - Python'
Algorithms Casts 9 mins
Minimum Absolute Difference in BST - Leetcode 530 - Python
YouTube video '530. Minimum Absolute Difference in BST | Binary Search Tree | InOrder | LeetCode Daily Challenge'
LeetCodeWithMonu 20 mins
530. Minimum Absolute Difference in BST | Binary Search Tree | InOrder | LeetCode Daily Challenge
YouTube video 'Minimum Absolute Difference in BST | Minimum Distance Between BST Nodes | Leetcode daily challenge'
BinaryMagic 15 mins
Minimum Absolute Difference in BST | Minimum Distance Between BST Nodes | Leetcode daily challenge
YouTube video 'Python Programming - Minimum Absolute Difference in BST | JavaScript, Java and C++ | LeetCode #530'
CodingNinja 6 mins
Python Programming - Minimum Absolute Difference in BST | JavaScript, Java and C++ | LeetCode #530
YouTube video 'Leetcode solving: 530. Minimum Absolute Difference in BST'
Math Geeks 3 mins
Leetcode solving: 530. Minimum Absolute Difference in BST
YouTube video 'Leetcode 530: Minimum Absolute Difference in BST | Efficient Solution'
Mohit Chhabra 13 mins
Leetcode 530: Minimum Absolute Difference in BST | Efficient Solution
YouTube video 'Day 242: LeetCode Problem 530. Minimum Absolute Difference in BST - Swift'
iOSxBank 12 mins
Day 242: LeetCode Problem 530. Minimum Absolute Difference in BST - Swift
YouTube video 'Mastering Binary Search Trees: Solving LeetCode 530 'Minimum Absolute Difference in BST' | Python'
vanAmsen 6 mins
Mastering Binary Search Trees: Solving LeetCode 530 'Minimum Absolute Difference in BST' | Python
19 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 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