Difficulty: Easy | Acceptance: 59.40% | Paid: No Topics: Tree, Depth-First Search, Breadth-First Search, Binary Search Tree, Binary Tree
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
- Examples
- Constraints
- Approach 1: In-order Traversal (Iterative)
- Approach 2: In-order Traversal (Recursive)
- Approach 3: Flatten and Compare
Examples
Input: root = [4,2,6,1,3]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
The given tree [4,2,6,1,3] is represented by the following diagram:
4
/ \
2 6
/ \
1 3
while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
Input: root = [1,0,48,null,null,12,49]
Output: 1
Explanation:
The minimum difference occurs between node 48 and node 12, and also between node 48 and node 49.
Constraints
- The number of nodes in the tree is in the range [2, 10^4].
- 0 <= Node.val <= 10^5
Approach 1: In-order Traversal (Iterative)
Intuition In-order traversal of a Binary Search Tree visits nodes in strictly ascending order. Therefore, the minimum absolute difference must exist between two adjacent nodes visited during this traversal.
Steps
- Initialize a stack to simulate the recursion and variables to track the previous node and the minimum difference found so far.
- While the stack is not empty or the current node is not null:
- Traverse to the leftmost node, pushing nodes onto the stack.
- Pop a node from the stack (this is the current node to process).
- If a previous node exists, calculate the difference between the current node’s value and the previous node’s value. Update the minimum difference if this new difference is smaller.
- Set the current node as the previous node for the next iteration.
- Move to the right child of the current node.
- Return the minimum difference found.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
stack = []
prev = None
min_diff = float('inf')
curr = root
while stack or curr:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
if prev is not None:
min_diff = min(min_diff, curr.val - prev.val)
prev = curr
curr = curr.right
return min_diffComplexity
- Time: O(N) — We visit each node exactly once.
- Space: O(H) — The stack stores at most the height of the tree (H). In the worst case (skewed tree), this is O(N).
- Notes: This is the most space-efficient approach for iterative solutions as it avoids storing all node values.
Approach 2: In-order Traversal (Recursive)
Intuition Similar to the iterative approach, we leverage the property of BST that in-order traversal yields sorted values. We use recursion to traverse the tree and maintain the previous node’s value and the minimum difference using class member variables or closures.
Steps
- Initialize member variables (or closure variables) to store the previous node value and the minimum difference.
- Define a recursive helper function to perform in-order traversal.
- In the helper function:
- Recursively call the function on the left child.
- Process the current node: if a previous node exists, update the minimum difference. Update the previous node to the current node.
- Recursively call the function on the right child.
- Start the recursion from the root and return the minimum difference.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.prev = None
self.min_diff = float('inf')
def inorder(node):
if not node:
return
inorder(node.left)
if self.prev is not None:
self.min_diff = min(self.min_diff, node.val - self.prev.val)
self.prev = node
inorder(node.right)
inorder(root)
return self.min_diffComplexity
- Time: O(N) — We visit each node exactly once.
- Space: O(H) — The recursion stack uses space proportional to the height of the tree.
- Notes: This approach is often cleaner to write than the iterative version but uses the call stack.
Approach 3: Flatten and Compare
Intuition We can perform an in-order traversal to collect all node values into a list. Since the list will be sorted, we can then iterate through the list once to find the minimum difference between adjacent elements.
Steps
- Initialize an empty list to store values.
- Perform an in-order traversal (iterative or recursive) of the BST, appending each node’s value to the list.
- Iterate through the list from index 1 to the end.
- For each element, calculate the difference with the previous element and update the global minimum difference.
- Return the minimum difference.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
values = []
def inorder(node):
if not node:
return
inorder(node.left)
values.append(node.val)
inorder(node.right)
inorder(root)
min_diff = float('inf')
for i in range(1, len(values)):
min_diff = min(min_diff, values[i] - values[i-1])
return min_diffComplexity
- Time: O(N) — Traversal takes O(N) and iterating through the list takes O(N).
- Space: O(N) — We store all N node values in the list.
- Notes: This approach is conceptually simple but uses more memory than the previous approaches because it stores the entire sequence of values.