Kth Smallest Element in a BST

Iterative inorder traversal — pop the k-th node visited.

Medium
Time O(h + k) Space O(h)
LeetCode
3 min read
tree bst inorder

Problem#

Given the root of a BST and an integer k, return the k-th smallest value.

Examples#

  • [3,1,4,null,2], k = 11
  • [5,3,6,2,4,null,null,1], k = 33

Constraints#

  • The number of nodes is n, 1 <= k <= n <= 10^4.

Approach#

Iterative inorder traversal: push left chain; pop, decrement k, return value if k == 0; otherwise descend into right subtree.

Solution#

Kth Smallest Element in a BST
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) { st.push(cur); cur = cur->left; }
cur = st.top(); st.pop();
if (--k == 0) return cur->val;
cur = cur->right;
}
return -1;
}
};

Editorial#

Inorder traversal of a BST visits values in sorted order. The iterative form lets us stop exactly at the k-th pop without traversing the rest, giving O(h + k) work rather than O(n).

Complexity#

  • Time: O(h + k).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.