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
Difficulty
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
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 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.
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.
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 | 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++ |
Videos
Similar Problems
- problem 532: K-diff Pairs in an Array
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
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