[LeetCode] 230. Kth Smallest Element in a BST
Problem
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Solution
Binary Search
class Solution {
public int kthSmallest(TreeNode root, int k) {
int countLeft = count(root.left);
if (k <= countLeft) return kthSmallest(root.left, k);
else if (k > countLeft+1) return kthSmallest(root.right, k-countLeft-1);
else return root.val; //k == countLeft+1
}
private int count(TreeNode root) {
int count = 0;
if (root == null) return count;
return count(root.left)+1+count(root.right);
}
}
In-Order Traversal Iteration
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null) {
stack.push(root);
root = root.left;
}
while (k != 0) {
TreeNode node = stack.pop();
k--;
if (k == 0) return node.val;
TreeNode cur = node.right;
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
}
return -1;
}
}
In-Order Traversal Recursion
class Solution {
int res = 0;
int count = 0;
public int kthSmallest(TreeNode root, int k) {
count = k;
helper(root);
return res;
}
private void helper(TreeNode root) {
if (root == null) return;
helper(root.left);
count--;
if (count == 0) res = root.val;
helper(root.right);
}
}
Road to Glory
對酒當歌,人生幾何? 譬如朝露,去日苦多。
161 声望
53 粉丝
推荐阅读
[LeetCode] 958. Check Completeness of a Binary Tree
Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possibl...
linspiration阅读 1.9k
【牛客小白月赛69】题解与分析A-F【蛋挞】【玩具】【开题顺序】【旅游】【等腰三角形(easy)】【等腰三角形(hard)】
🎈 作者:Eriktse🎈 简介:19岁,211计算机在读,现役ACM银牌选手🏆力争以通俗易懂的方式讲解算法!❤️欢迎关注我,一起交流C++/Python算法。(优质好文持续更新中……)🚀🎈 个人博客:www.eriktse.com
Eriktse阅读 526
BFS算法模板与练习
文章和代码已经归档至【Github仓库:algorithms-notes】或者公众号【AIShareLab】回复 算法笔记 也可获取。首先,计算机中常用的数据结构是栈和队列。栈:先进后出,通常应用是递归,DFS。队列:先进先出,通常应...
YOLO阅读 206
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。