题目
Given a binary search tree,
write a function k-th Smallest to find the k-th smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
思路
对搜索二叉树(BST)进行中序遍历, 得到便是有序的序列.
既可以把中序遍历的序列用数组来保存, 返回array[k-1]即可,
但是空间复杂度为O(N), N为节点数.
也可以在中序遍历的过程中直接返回k-th小的数, 如代码中`method 2`.
code
/**
* 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 inorder(const TreeNode* root, vector<int>& arr) {
if(root == NULL) return;
inorder(root->left, arr);
arr.push_back(root->val);
inorder(root->right, arr);
}
void inorder(const TreeNode* root, const int k, int& res, int& c) {
if(c == -1) return;
if(root == NULL) {
c++;
return;
}
inorder(root->left, k, res, c);
if(c == k) {
res = root->val;
c = -1;
return;
}
inorder(root->right, k, res, c);
}
int kthSmallest(TreeNode* root, int k) {
/// method 1
// vector<int> arr;
// inorder(root, arr);
// return arr[k - 1];
/// method 2
int c = 0, res;
inorder(root, k, res, c);
return res;
}
};