/**
* 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:
bool inorder(TreeNode *root, int k, int &d, int &res) {
if (!root) return false;
if (inorder(root->left, k, d, res)) {
return true;
}
d++;
if (d == k) {
res = root->val;
return true;
}
if (inorder(root->right, k, d, res)) {
return true;
}
return false;
}
int kthSmallest(TreeNode* root, int k) {
int res;
int d = 0;
inorder(root, k, d, res);
return res;
}
};Kth Smallest Element in a BST
最新推荐文章于 2022-04-14 14:33:13 发布
本文介绍了一种使用C++实现的方法,通过中序遍历二叉搜索树来找到第K小的元素。这种方法适用于解决一些特定类型的编程问题,如在不完全排序的情况下快速找到有序序列中的特定位置元素。
546

被折叠的 条评论
为什么被折叠?



