Kth Smallest Element in a BST
Iterative inorder traversal — pop the k-th node visited.
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 = 1→1[5,3,6,2,4,null,null,1], k = 3→3
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#
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; }};func kthSmallest(root *TreeNode, k int) int { st := []*TreeNode{} cur := root for cur != nil || len(st) > 0 { for cur != nil { st = append(st, cur) cur = cur.Left } cur = st[len(st)-1] st = st[:len(st)-1] k-- if k == 0 { return cur.Val } cur = cur.Right } return -1}from typing import Optional
class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: st = [] cur = root while cur or st: while cur: st.append(cur) cur = cur.left cur = st.pop() k -= 1 if k == 0: return cur.val cur = cur.right return -1function kthSmallest(root, k) { const st = []; let cur = root; while (cur || st.length) { while (cur) { st.push(cur); cur = cur.left; } cur = st.pop(); if (--k === 0) return cur.val; cur = cur.right; } return -1;}class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> st = new ArrayDeque<>(); TreeNode cur = root; while (cur != null || !st.isEmpty()) { while (cur != null) { st.push(cur); cur = cur.left; } cur = st.pop(); if (--k == 0) return cur.val; cur = cur.right; } return -1; }}function kthSmallest(root: TreeNode | null, k: number): number { const st: TreeNode[] = []; let cur: TreeNode | null = root; while (cur || st.length) { while (cur) { st.push(cur); cur = cur.left; } cur = 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#
Related#