#783
Minimum Distance Between BST Nodes
EasyTreeDepth-First SearchBreadth-First SearchBinary Search TreeBinary TreeIn-order TraversalSortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution takes advantage of the properties of a BST. By performing an in-order traversal, we can ensure that the values are collected in sorted order. This allows us to simply compare adjacent values to find the minimum difference, which is much more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Perform an in-order traversal of the BST to collect values in a sorted list.
- 2Step 2: Initialize a variable to store the minimum difference, set it to a large number.
- 3Step 3: Iterate through the sorted list and compare each value with the next one to find the minimum difference.
solution.py19 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def minDiffInBST(root):
9 values = []
10 def inorder(node):
11 if node:
12 inorder(node.left)
13 values.append(node.val)
14 inorder(node.right)
15 inorder(root)
16 min_diff = float('inf')
17 for i in range(1, len(values)):
18 min_diff = min(min_diff, values[i] - values[i - 1])
19 return min_diffℹ
Complexity note: The time complexity is O(n) because we traverse each node once, and the space complexity is O(n) due to storing the values in a list.
- 1In a BST, in-order traversal yields sorted values.
- 2The minimum difference will always be between adjacent values in the sorted list.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.