Leetcode 530. Minimum Absolute Difference in BST
Problem Statement
Given a binary search tree (BST) with distinct values, find the minimum absolute difference between the values of any two nodes in the tree.
Clarifying Questions
- Input Constraints:
- Are the values in the BST all distinct?
- Yes, the values are distinct.
- What is the range of the number of nodes in the tree?
- Typically 1 <= Nodes <= 10^4.
- Are negative values allowed in the BST?
- Yes, both negative and positive values are allowed.
- What should we return if the BST contains only one node?
- Ideally, this case wouldn’t be given as there are no two nodes to compare. However, we can assume a default return value (e.g., Integer.MAX_VALUE) or not handle it unless specified.
Strategy
- In-Order Traversal: Since the BST’s inorder traversal gives nodes in non-decreasing order, the difference between consecutive elements in this traversal will naturally include the minimum absolute difference.
- Track Minimum Difference: As we traverse, compare the current node with the previous node and keep track of the smallest difference.
- Space & Time Efficiency: Use an iterative approach or recursion with constant extra space apart from the recursion stack to process nodes.
Code
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public int getMinimumDifference(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
TreeNode prev = null;
int minDifference = Integer.MAX_VALUE;
while (!stack.isEmpty() || current != null) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
if (prev != null) {
minDifference = Math.min(minDifference, Math.abs(current.val - prev.val));
}
prev = current;
current = current.right;
}
return minDifference;
}
}
Explanation
- Initialization: Use a stack to simulate the recursive in-order traversal of a BST.
- In-Order Traversal: Traverse to the leftmost node and push each node onto the stack until reaching a null reference.
- Node Processing: Pop nodes from the stack to process:
- Compare the current node’s value with the previous node’s value.
- Update the minimum difference if the current difference is smaller.
- Move to the right subtree to continue the traversal.
- Termination: The process continues until all nodes are traversed and the stack is empty.
Time Complexity
- Time Complexity: O(n), where n is the number of nodes in the BST. Each node is visited exactly once.
- Space Complexity: O(h), where h is the height of the tree. This space is used by the stack. In the worst case (a completely unbalanced tree), it can be O(n). In the best case (a balanced tree), it is O(log n).
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?