Kth Smallest Element in a BST (Medium)

Kth Smallest Element in a BST (Medium)

·

3 min read

Given the root of a binary search tree, and an integer k, return the k<sup>th</sup> smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

1) Explain the problem

We need to find the k-th smallest value in a binary search tree (BST). In a BST, the left subtree of a node contains only nodes with values less than the node's value, and the right subtree only contains nodes with values greater than the node's value.

2) Short easy to remember solution/approach

Perform an in-order traversal of the BST, which visits nodes in ascending order. Keep track of the count of nodes visited and return the k-th node visited.

3) Solution in Javascript with code commenting

class TreeNode {
    constructor(val, left = null, right = null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

function kthSmallest(root, k) {
    let count = 0;
    let result = null;

    function inOrderTraversal(node) {
        if (!node || result !== null) return;

        // Traverse the left subtree
        inOrderTraversal(node.left);

        // Visit the current node
        count++;
        if (count === k) {
            result = node.val;
            return;
        }

        // Traverse the right subtree
        inOrderTraversal(node.right);
    }

    // Start in-order traversal from the root
    inOrderTraversal(root);
    return result;
}

// Example usage:
let root = new TreeNode(3);
root.left = new TreeNode(1);
root.right = new TreeNode(4);
root.left.right = new TreeNode(2);

console.log(kthSmallest(root, 1)); // Output: 1
console.log(kthSmallest(root, 2)); // Output: 2
console.log(kthSmallest(root, 3)); // Output: 3

4) Explanation of the solution in an easy-to-understand way. Explain it like a 10yo.

Imagine you have a bookshelf where books are arranged in order by size. You want to find the k-th smallest book. You start from the leftmost book and count each book until you reach the k-th book. That’s the book you want!

5) Code explanation in pointers

  • Define a TreeNode class to represent each node in the tree.

  • Create a kthSmallest function that:

    • Initializes a counter count and a result variable result.

    • Defines a helper function inOrderTraversal to perform in-order traversal:

      • If the node is null or the result is already found, return.

      • Recursively traverse the left subtree.

      • Visit the current node, increment the counter, and check if it matches k.

      • Recursively traverse the right subtree.

    • Start the in-order traversal from the root.

    • Return the result.

6) Complexities

  • Time Complexity: (O(n)) - In the worst case, we might visit all nodes.

  • Space Complexity: (O(h)) - Where (h) is the height of the tree. This is due to the recursion stack used for in-order traversal.