LeetCode Solutions
530. Minimum Absolute Difference in BST
Time: $O(n)$ Space: $O(\log n)$
class Solution {
public:
// Very simliar to 94. Binary Tree Inorder Traversal
int getMinimumDifference(TreeNode* root) {
int ans = INT_MAX;
int prev = -1;
stack<TreeNode*> stack;
while (root || !stack.empty()) {
while (root) {
stack.push(root);
root = root->left;
}
root = stack.top(), stack.pop();
if (prev >= 0)
ans = min(ans, root->val - prev);
prev = root->val;
root = root->right;
}
return ans;
}
};
class Solution {
// Very simliar to 94. Binary Tree Inorder Traversal
public int getMinimumDifference(TreeNode root) {
int ans = Integer.MAX_VALUE;
int prev = -1;
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (prev >= 0)
ans = Math.min(ans, root.val - prev);
prev = root.val;
root = root.right;
}
return ans;
}
}