LeetCode 230: Kth Smallest Element in a BST

Problem Description

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.

Solutions

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;
    }
}

Loading editor...