当前位置:网站首页>Sword finger offer 54 The k-th node of binary search tree
Sword finger offer 54 The k-th node of binary search tree
2022-07-18 20:54:00 【anieoo】
Original link : The finger of the sword Offer 54. The second of binary search tree k Big node
solution:
The middle order traversal of binary search tree is an ascending array , Go back to k A big number is enough
/**
* 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:
vector<int> inorder;
int kthLargest(TreeNode* root, int k) {
dfs(root);
return inorder[inorder.size() - k];
}
void dfs(TreeNode *root) {
if(root == NULL) return;
dfs(root->left);
inorder.push_back(root->val);
dfs(root->right);
}
};Reverse middle order traversal , In calculating the number of traversal nodes , Reduce memory consumption
/**
* 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 ans = 0,cnt = 0;
int kthLargest(TreeNode* root, int k) {
dfs(root, k);
return ans;
}
void dfs(TreeNode *root, int k) {
if(root == NULL) return;
dfs(root->right, k);
if(++cnt == k) {
ans = root->val;
return;
}
dfs(root->left, k);
}
};边栏推荐
- YOLOv5改进之二十:Involution新神经网络算子引入网络
- Opencv tutorial 02: core operations of opencv
- Flutter 绘制非常有趣的贝塞尔曲线动画
- SAP AppGyver 简介
- JS speed up video playback
- The first ide overlord in the universe, replaced...
- Electron installation configuration
- R语言ggplot2可视化:ggplot2可视化密度图(density plot)并使用geom_vline函数添加均值竖线、添加均值数值标签(Mean Line or Vertical Line )
- Flutter modifies the color of the status bar separately for each page
- SF city test development side 49min answer
猜你喜欢

leetcode:1552. 两球之间的磁力【最值的最值 = 二分】

Three ways for industrial parks to enhance the service capacity of enterprises

产业园区如何做好精细化运营管理

顺丰同城测试开发一面 49min答案

浅谈数组方法重构再封装-forEach-Map——push(),unshift(),shift(),Map(),filter(),every(),some(), reduce()

There is something that turns vscode into an idea effect

Applet page navigation

Basic research on Chang'an chain TLS

OpenCV 教程 02: OpenCV 的核心操作

待处理问题
随机推荐
每日刷题记录 (二十五)
程序员都不懂的代码
Applet page navigation
激活navicat提示rsa public key not find的问题
Little sister, I'm coming
记住这几点就能快速的去找到bug
MySQL查看数据库性能常用命令
Simple example of xgboost+word2vec text classification
nexus5 root 刷机
1.爬虫概述
数据统计分析案例(对比分析、销量定比分析、同比、双坐标图、环比、shift、贡献度分析(帕累托法则)、差异化分析、resample、季节性波动分析)
BRITS: Bidirectional Recurrent Imputation for Time Series(时间序列的双向递归填补)论文详解
The first ide overlord in the universe, replaced...
scrcpy投屏
Flutter modifies the color of the status bar separately for each page
高数下|二重积分的概念及性质|高数叔|手写笔记
21、当在浏览器中输入了URL之后,程序是怎样执行的?
待处理问题
Dynamic memory management (C language)
我是猪代码