当前位置:网站首页>230. 二叉搜索树中第K小的元素
230. 二叉搜索树中第K小的元素
2022-07-21 05:15:00 【安吉_lh1029】
1、题目描述
2、题目分析
要寻找二叉搜索树中排序在第k个元素的位置,等价于需要把二叉搜索树进行【升序】排序。
即对应的转换为把二叉搜索树,转换为【中序】遍历,并存在容器中,可以是list, 数组,或者哈希表,队列均可以。
然后获取第k个位置,如本题我是使用list, index下标从0开始,因此第k个元素,即获取下标为k-1的元素即可,list.get(k-1); 代码如下:
class Solution {
//二叉树进行中序遍历
List<Integer> list = new ArrayList<Integer>();
public int kthSmallest(TreeNode root, int k) {
if(root == null) return -1;
//此时list就是升序排列的
dfs(root);
if(list.size() >= k)
return list.get(k-1);
return -1;
}
private void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
}
复杂度分析:
时间复杂度 O(N):中序遍历,每个元素都遍历到,因此复杂度为 O(N)。
空间复杂度 O(N):list中包含了全部元素,因此空间复杂度为O(N).
在上面基础上进行时间和空间复杂度度优化,即一旦获取到第k个元素,即停止。无需遍历全部到元素。
class Solution {
int res;
int sortK; // 排序后到第k个元素,这个需要是全局变量
public int kthSmallest(TreeNode root, int k) {
//【中序遍历】
this.sortK = k;
dfs(root);
return res;
}
private void dfs(TreeNode root){
if(root == null || sortK <= 0) return;
dfs(root.left);
if(--sortK == 0) res = root.val;
dfs(root.right);
}
}
复杂度分析:
时间复杂度:令 h 为树高,先到达叶子位置(最小节点位置),复杂度为 O(h),然后找到第 k 小的元素,复杂度为 O(k)。 整体 复杂度为 O(h+k)
空间复杂度:令 h 为树高,复杂度为 O(h)
边栏推荐
- 994. 腐烂的橘子
- 01 knapsack interview questions series (I)
- ArrayList源码深度剖析,从最基本的扩容原理,到魔幻的迭代器和fast-fail机制,你想要的这都有!!!
- Task and Await: Consuming Awaitable Methods
- Qt5 GUI
- Scratch graphical programming operation hardware
- 手把手教你在服务器上用YOLOv4训练和测试数据集(保姆级)
- Common shortcut keys of robotframework
- In depth analysis of multiple knapsack problem (Part 1)
- 概率论-假设检验
猜你喜欢
一文讲透,分布式系统的数据分片难题
108. 将有序数组转换为二叉搜索树
干货 | 分布式系统的数据分片难题
Concurrency opening -- take you from 0 to 1 to build the cornerstone of concurrency knowledge system
Vs2019+opencv installation and configuration tutorial
226. 翻转二叉树
Super practical 12 SQL optimization schemes
你觉得分库分表真的适合你的系统吗?聊聊分库分表和NewSQL如何选择
西瓜书第二章-比较检验
04-unittest单元测试框架
随机推荐
In depth analysis of LinkedList source code
Yolov4 (Darknet version) post processing: display confidence and save the contents of the detection box locally
干货 | 分布式系统的数据分片难题
What are the functions and application industries of testing equipment development?
ArrayList源码深度剖析,从最基本的扩容原理,到魔幻的迭代器和fast-fail机制,你想要的这都有!!!
What are the problems in the classification and future development of IOT devices?
使用MySQL,请善用 JSON 这张牌
Do you still have certificates to participate in the open source community?
Interviewer: have you made a judgment on the number of rows affected by your update?
04-unittest單元測試框架
Task and Await: Consuming Awaitable Methods
Does NMN product really have its effect? What effect does it have after taking NMN for several months
Qt5 GUI
YOLOv4(darknet版)后处理:显示置信度、保存检测框的内容到本地
Application advantages of WiFi module in the Internet of things
04 cadre d'essai de l'unit é unitest
堆-原理到应用——堆排序、优先级队列
Heap - principle to application - heap sorting, priority queue
01背包面试题系列(一)
Liteos opening