230. Kth Smallest Element in a BST

来源:互联网 发布:java 实现syslog 编辑:程序博客网 时间:2024/05/21 11:12

题目描述【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];    }};