LeetCode 530: Minimum Absolute Difference in BST Solution

Master LeetCode problem 530 (Minimum Absolute Difference in BST), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To find the minimum absolute difference in a Binary Search Tree (BST), we can perform an in-order traversal of the tree which will give us the nodes in sorted order. During the traversal, we can compare adjacent nodes to find the minimum absolute difference.

  1. Perform an in-order traversal of the BST to get the nodes in sorted order.
  2. Keep track of the previous node value during the traversal and calculate the absolute difference with the current node value.
  3. Update the minimum absolute difference if a smaller difference is found.
  4. Return the minimum absolute difference at the end.

Time Complexity: O(n) - where n is the number of nodes in the BST Space Complexity: O(h) - where h is the height of the BST

Solution Code

class Solution {
    int minDiff = Integer.MAX_VALUE;
    Integer prev = null;

    public int getMinimumDifference(TreeNode root) {
        inorder(root);
        return minDiff;
    }

    private void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        if (prev != null) {
            minDiff = Math.min(minDiff, root.val - prev);
        }
        prev = root.val;
        inorder(root.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 530 (Minimum Absolute Difference in BST)?

This page provides optimized solutions for LeetCode problem 530 (Minimum Absolute Difference in BST) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 530 (Minimum Absolute Difference in BST)?

The time complexity for LeetCode 530 (Minimum Absolute Difference in BST) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 530 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 530 in Java, C++, or Python.

Back to LeetCode Solutions