00:00

Problem Statement

Input/Output Examples

Visual Explanation

Stopping at the k-th node means only the path to the smallest node plus k visits are needed, not the whole tree.

Approaches

Both approaches walk the tree in order and stop at the k-th value. One uses a stack; the other recursion.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here h is the tree height. The traversal walks down to the smallest node and then visits k nodes.

Interview Tips and Recommended Approach

  • Use the BST order. There is no need to collect and sort all values.
  • Stop early. Collecting the whole traversal first costs O(n) time and memory.
  • Know the follow-up. If the tree changes often, store subtree sizes in each node for O(h) queries.
  • Avoid static state in real code; pass a small counter object instead.

Recommended Approach: Iterative Inorder With Early Stop

Why: it reuses the standard iterative inorder traversal, stops at the answer and needs no recursion.