给定一个二叉搜索树,编写一个函数 kthSmallest
来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 输出: 3
C
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void func(struct TreeNode* root, int* tmp, int* t)
{
if(root)
{
tmp[*t]=root->val;
(*t)++;
func(root->left,tmp,t);
func(root->right,tmp,t);
}
}
void sort(int *a, int left, int right)
{
if(left >= right)
{
return ;
}
int i = left;
int j = right;
int key = a[i];
while(i < j)
{
while(i < j && key <= a[j])
{
j--;
}
a[i] = a[j];
while(i < j && key >= a[i])
{
i++;
}
a[j] = a[i];
}
a[i] = key;
sort(a, left, i - 1);
sort(a, i + 1, right);
}
int kthSmallest(struct TreeNode* root, int k)
{
int* tmp=(int*)malloc(sizeof(int)*10000);
int t=0;
func(root,tmp,&t);
quicksort(tmp,0,t-1);
return tmp[k-1];
}
C++
/**
* 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:
void func(TreeNode* root, vector<int>& tmp)
{
if(root)
{
tmp.push_back(root->val);
func(root->left,tmp);
func(root->right,tmp);
}
}
int kthSmallest(TreeNode* root, int k)
{
vector<int> tmp;
func(root,tmp);
sort(tmp.begin(),tmp.end());
return tmp[k-1];
}
};
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def func(self,root,tmp):
if root:
tmp.append(root.val)
tmp=self.func(root.left,tmp)
tmp=self.func(root.right,tmp)
return tmp
def kthSmallest(self, root: TreeNode, k: int) -> int:
tmp=[]
tmp=self.func(root,tmp)
tmp.sort()
return tmp[k-1]