LeetCode 230: Kth Smallest Element in a BST Solution

Master LeetCode problem 230 (Kth Smallest Element in a BST), a medium 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.

230. Kth Smallest Element in a BST

Problem Explanation

Explanation

To find the kth smallest element in a BST, we can perform an in-order traversal of the BST which will give us the elements in sorted order. While doing the in-order traversal, we keep track of the count of elements visited so far. When the count reaches k, we return the current node's value.

  1. Initialize a variable count to keep track of the number of elements visited so far.
  2. Perform an in-order traversal of the BST.
  3. When visiting a node, increment the count.
  4. If count becomes equal to k, return the value of the current node.
  5. If not, continue the traversal until the end.
  6. The kth smallest element will be the value returned when count equals k.

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 {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        int count = 0;

        while (current != null || !stack.isEmpty()) {
            while (current != null) {
                stack.push(current);
                current = current.left;
            }

            current = stack.pop();
            count++;

            if (count == k) {
                return current.val;
            }

            current = current.right;
        }

        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 230 (Kth Smallest Element in a BST)?

This page provides optimized solutions for LeetCode problem 230 (Kth Smallest Element in a 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 230 (Kth Smallest Element in a BST)?

The time complexity for LeetCode 230 (Kth Smallest Element in a BST) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 230 on DevExCode?

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

Back to LeetCode Solutions