当前位置:网站首页>【剑指Offer】54. 二叉搜索树的第k大节点
【剑指Offer】54. 二叉搜索树的第k大节点
2022-07-01 13:26:00 【LuZhouShiLi】
剑指 Offer 54. 二叉搜索树的第k大节点
题目
给定一棵二叉搜索树,请找出其中第 k 大的节点的值。
思路
按照二叉搜索树的中序遍历倒序的第K个节点
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
int res;
int kthLargest(TreeNode* root, int k) {
dfs(root,k);
return res;
}
void dfs(TreeNode *root, int &k)
{
// 中序遍历 倒序:右节点->根结点->左节点
if(!root) return ;
dfs(root->right,k);
k--;
if(!k) res = root->val; // 当k等于0 说明找到目标节点 无需继续遍历
dfs(root->left,k);// 左
}
};
边栏推荐
- Report on the current situation and development trend of bidirectional polypropylene composite film industry in the world and China Ⓟ 2022 ~ 2028
- 04-Redis源码数据结构之字典
- French Data Protection Agency: using Google Analytics or violating gdpr
- 10. Page layout, guess you like it
- Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
- Analysis report on the development prospect and investment strategic planning of China's wafer manufacturing Ⓔ 2022 ~ 2028
- arthas使用
- Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
- Machine learning summary (I): linear regression, ridge regression, Lasso regression
- Blind box NFT digital collection platform system development (build source code)
猜你喜欢

AnimeSR:可学习的降质算子与新的真实世界动漫VSR数据集

陈宇(Aqua)-安全->云安全->多云安全

龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍

一文读懂TDengine的窗口查询功能

研发效能度量框架解读

当你真的学会DataBinding后,你会发现“这玩意真香”!

Computer network interview knowledge points

【241. 为运算表达式设计优先级】

Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
![[241. Design priority for operation expression]](/img/72/29d27204d5213a8efdb2c5be925dec.png)
[241. Design priority for operation expression]
随机推荐
minimum spanning tree
研发效能度量框架解读
Spark source code reading outline
Sign APK with command line
The 14th five year plan of China's environmental protection industry and the report on the long-term goals for 2035 Ⓖ 2022 ~ 2028
进入前六!博云在中国云管理软件市场销量排行持续上升
Use of shutter SQLite
6. Wiper part
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
单工,半双工,全双工区别以及TDD和FDD区别
2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!
机器学习总结(一):线性回归、岭回归、Lasso回归
Solution to 0xc000007b error when running the game [easy to understand]
Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
2.15 summary
Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
Svg diamond style code
啟動solr報錯The stack size specified is too small,Specify at least 328k
Introduction to topological sorting
Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme