Algo-Sim › Binary Trees & BST
Kth Smallest Element in a BST
Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input
An iterative inorder walk reaches BST values in ascending order; stop at the kth one.
Problem
Given the root of a binary search tree and k, return the kth smallest value in the tree, counting from 1.
Constraints
- 1 ≤ k ≤ n ≤ 10⁴ (n = number of nodes)
- 0 ≤ Node.val ≤ 10⁴
Edge cases to test
- k = 1: the minimum
- k = n: the maximum
- A skewed tree
Follow-up questions
- What if the tree changes often and you query often?
- Store each node’s subtree size, then pick left or right by size: O(h) per query and update.
- What is the cost of the inorder walk?
- O(h + k): it stops as soon as it reaches the k-th value.
Solution
Java
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode curr = root;
while (true) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
if (--k == 0) return curr.val;
curr = curr.right;
}
}Python
def kth_smallest(root, k):
stack = []
curr = root
while True:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
k -= 1
if k == 0:
return curr.val
curr = curr.rightC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int kthSmallest(TreeNode *root, int k) {
deque<TreeNode *> stack = {};
TreeNode *curr = root;
while (true) {
while (curr != nullptr) {
stack.push_back(curr);
curr = curr->left;
}
curr = stack.back();
stack.pop_back();
if (--k == 0)
return curr->val;
curr = curr->right;
}
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)