题解 | #第k轻的牛牛# 二叉搜索树
第k轻的牛牛
https://www.nowcoder.com/practice/d3b31f055b1640d9b10de0a6f2b8e6f3
知识点
二叉搜索树
思路
要求出二叉树中第k小的值,二叉搜索树的中序遍历得到的是递增序列,因此只要跑中序遍历,搜索个数达到k后更新答案并及时剪枝。
时间复杂度
由于及时剪枝,总体时间复杂度是
AC code (C++)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <queue>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return int整型
*/
int kthLighest(TreeNode* root, int k) {
int res = 0;
int cnt = 0;
function<void(TreeNode*)> dfs = [&](TreeNode* root) {
if (!root or cnt >= k) return;
dfs(root->left);
if ( ++ cnt == k) {
res = root->val;
return;
}
dfs(root->right);
};
dfs(root);
return res;
}
};

查看12道真题和解析
