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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 94: Binary Tree Inorder Traversal
Solved On The Same Day
- problem 796: Rotate String
- problem 393: UTF-8 Validation
- problem 787: Cheapest Flights Within K Stops
- problem 788: Rotated Digits
Extra
- 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