LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)
230. 二叉搜索树中第K小的元素
230. Kth Smallest Element in a BST
题目描述
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
LeetCode230. Kth Smallest Element in a BST
示例 1:
3
/ \
1 4
\
2
输出: 1
示例 2:
5
/ \
3 6
/ \
2 4
/
1
输出: 3
进阶:
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
Java 实现
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public int kthSmallest(TreeNode root, int k) {
int count = countNodes(root.left);
if (k <= count) {
return kthSmallest(root.left, k);
} else if (k > count + 1) {
return kthSmallest(root.right, k - 1 - count);
}
return root.val;
}
public int countNodes(TreeNode n) {
if (n == null) {
return 0;
}
return 1 + countNodes(n.left) + countNodes(n.right);
}
}
相似题目
参考资料
- https://leetcode.com/problems/kth-smallest-element-in-a-bst/
- https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

更多精彩