Skip to content

530. Minimum Absolute Difference in BST 👍

  • Time: $O(n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  // Similar to 94. Binary Tree Inorder Traversal
  int getMinimumDifference(TreeNode* root) {
    int ans = INT_MAX;
    int prev = -1;
    stack<TreeNode*> stack;

    while (root != nullptr || !stack.empty()) {
      while (root != nullptr) {
        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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  // Similar 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;
  }
}