leetcode-230-二叉搜索树中第K小的元素
[博客链接]
[题目链接]
[github地址]
[题目描述]
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
示例 1:
输入:root = [3,1,4,null,2], k = 1
输出:1
示例 2:
输入:root = [5,3,6,2,4,null,null,1], k = 3
输出:3
提示:
- 树中的节点数为 n 。
- 1 <= k <= n <=
- 0 <= Node.val <=
思路一:中序遍历
- 因为搜索二叉树本身中序遍历即可保持有序
- 中序遍历即可
class Solution {
//思路一:中序遍历
//中序遍历后直接查结果就行
List<Integer> list = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
if (root == null) {
return 0;
}
inOrder(root);
return list.get(k - 1);
}
public void inOrder(TreeNode root) {
if (root.left != null) {
inOrder(root.left);
}
list.add(root.val);
if (root.right != null) {
inOrder(root.right);
}
}
}
- 时间复杂度: lgn表示树的高度的大概值、n表示节点数量
- 空间复杂度:
思路二:排序
- 排序后返回固定索引位置即可
- 题目给出了频繁增删的操作前提,所以不建议使用这种办法
class Solution {
List<Integer> list = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
dfs(root);
Collections.sort(list);
return list.get(k - 1);
}
void dfs(TreeNode root) {
if (root == null) return ;
list.add(root.val);
dfs(root.left);
dfs(root.right);
}
}
- 时间复杂度:
- 空间复杂度:
思路三:优先队列
- 其实也是排序的一种
- 通过优先队列实现堆排,然后出入队列返回即可
- 就不写代码了
- 时间复杂度:
- 空间复杂度: