题目描述【Leetcode】
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ? k ? BST’s total elements.
找出二叉搜索树的第k小的数,用递归再排序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void f(TreeNode * root, vector<int>& re){
if(!root) return;
re.push_back(root->val);
f(root->left,re);
f(root->right,re);
}
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if(!root) return 0;
vector<int>re;
f(root,re);
sort(re.begin(),re.end());
return re[k-1];
}
};

本文介绍了一种利用递归与排序方法求解二叉搜索树中第K小元素的问题。通过定义一个辅助函数进行节点遍历并将节点值收集到一个向量中,然后对向量进行排序,从而找到第K小的元素。
534

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



