#530

Minimum Absolute Difference in BST

Easy
TreeDepth-First SearchBreadth-First SearchBinary Search TreeBinary TreeIn-order TraversalTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution leverages the properties of a BST and performs an in-order traversal to find the minimum absolute difference in a single pass. This is efficient because the in-order traversal produces a sorted list of values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the previous node's value and the minimum difference.
  2. 2Step 2: Perform an in-order traversal of the BST, updating the minimum difference whenever a new node is visited.
  3. 3Step 3: Return the minimum difference found.
solution.py21 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
8class Solution:
9    def getMinimumDifference(self, root: TreeNode) -> int:
10        self.prev = None
11        self.min_diff = float('inf')
12        self.inorder_traversal(root)
13        return self.min_diff
14
15    def inorder_traversal(self, node):
16        if node:
17            self.inorder_traversal(node.left)
18            if self.prev is not None:
19                self.min_diff = min(self.min_diff, abs(node.val - self.prev))
20            self.prev = node.val
21            self.inorder_traversal(node.right)

Complexity note: The time complexity is O(n) because we visit each node exactly once during the in-order traversal. The space complexity is O(h), where h is the height of the tree, due to the recursion stack.

  • 1In a BST, in-order traversal yields sorted values, making it easier to find minimum differences.
  • 2The minimum absolute difference will always be between adjacent nodes in the sorted order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.