Practice › Trees
Kth Smallest Element in a BST
Medium · Trees · Asked at Amazon, Google, Uber, Bloomberg
The tree is a binary search tree with distinct values. Print the k-th smallest value (1-based).
Input
First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: k.
Output
The k-th smallest value.
Constraints
- 1 ≤ k ≤ number of nodes ≤ 10^4
An inorder traversal of a BST visits values in increasing order — stop at the k-th one.
Example 1
Input
5 3 1 4 -1 2 1
Output
1
Example 2
Input
8 5 3 6 2 4 -1 -1 1 3
Output
3
Hints
- Inorder traversal of a BST lists its values in increasing order.
- Do an iterative inorder traversal and stop at the k-th visited node.
Approach
Iterative inorder with a stack: push nodes while moving left, pop one, count it — if the counter reaches k, that value is the answer — then continue with its right child. We stop after k visits, so the cost is O(h + k).
Complexity: O(h + k) time · O(h) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// Build a tree from level order where -1 means "no node".
Node *readTree() {
int k;
cin >> k;
vector<long long> v(k);
for (auto &x : v) cin >> x;
if (k == 0 || v[0] == -1) return nullptr;
Node *root = new Node(v[0]);
queue<Node *> q;
q.push(root);
int i = 1;
while (!q.empty() && i < k) {
Node *cur = q.front();
q.pop();
if (i < k && v[i] != -1) q.push(cur->left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.push(cur->right = new Node(v[i]));
i++;
}
return root;
}
int main() {
Node *cur = readTree();
int k;
cin >> k;
stack<Node *> st;
while (cur || !st.empty()) {
while (cur) st.push(cur), cur = cur->left;
cur = st.top();
st.pop();
if (--k == 0) {
cout << cur->val << "\n";
return 0;
}
cur = cur->right;
}
return 0;
}Python solution
import sys
from collections import deque
sys.setrecursionlimit(100000)
class Node:
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build_tree(v):
"""Build a tree from level order where -1 means "no node"."""
if not v or v[0] == -1:
return None
root = Node(v[0])
q, i = deque([root]), 1
while q and i < len(v):
cur = q.popleft()
if i < len(v) and v[i] != -1:
cur.left = Node(v[i])
q.append(cur.left)
i += 1
if i < len(v) and v[i] != -1:
cur.right = Node(v[i])
q.append(cur.right)
i += 1
return root
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build_tree(data[1 : 1 + k])
rest = data[1 + k :]
k, cur, st = rest[0], root, []
while cur or st:
while cur:
st.append(cur)
cur = cur.left
cur = st.pop()
k -= 1
if k == 0:
print(cur.val)
break
cur = cur.rightJava solution
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// Build a tree from level order where -1 means "no node".
static Node readTree(Scanner sc) {
int k = sc.nextInt();
long[] v = new long[k];
for (int i = 0; i < k; i++) v[i] = sc.nextLong();
if (k == 0 || v[0] == -1) return null;
Node root = new Node(v[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < k) {
Node cur = q.poll();
if (i < k && v[i] != -1) q.add(cur.left = new Node(v[i]));
i++;
if (i < k && v[i] != -1) q.add(cur.right = new Node(v[i]));
i++;
}
return root;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Node cur = readTree(sc);
int k = sc.nextInt();
Deque<Node> st = new ArrayDeque<>();
while (cur != null || !st.isEmpty()) {
while (cur != null) { st.push(cur); cur = cur.left; }
cur = st.pop();
if (--k == 0) {
System.out.println(cur.val);
return;
}
cur = cur.right;
}
}
}Solve Kth Smallest Element in a BST online · All practice problems