题目
第一时间想到的题解
看到这二叉搜索树的查找,我的第一时间,就想到的中序遍历转有序数组,直接存取。
class Solution {
public:
vector<int>res;
int kthSmallest(TreeNode* root, int k) {
inorder(root);
return res[k-1];
}
private:
void inorder(TreeNode* root){
if(!root)
return;
inorder(root->left);
res.push_back(root->val);
inorder(root->right);
}
};
而后又有了基本的递归求解方法
class Solution {
public:
int n = 0;
int res = 0;
int kthSmallest(TreeNode* root, int k) {
inorder(root,k);
return res;
}
private:
void inorder(TreeNode* root,int k){
if(!root)
return;
if(n>k)
return;
inorder(root->left,k);
//由于中序遍历都是在这里操作结点,所以从这里开始计数
n++;
if(n==k){res = root->val;return;}
inorder(root->right,k);
}
};
再然后就用了迭代法
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*>St;
//记录序数和答案
int n = 0;
int res = 0;
//一直push左子树
while(root){
St.push(root);
root = root->left;
}
//开始中序模拟
while(!St.empty()){
TreeNode* t = St.top();
//每遍历完一个n+1
St.pop();
n++;
if(n==k){
res = t->val;
break;
}
//一旦右子树不为空,则继续push
if(t->right){
St.push(t->right);
//一旦右子树的左子树不为空,继续push
if(t->right->left){
t = t->right->left;
while(t){
St.push(t);
t = t->left;
}
}
}
}
return res;
}
};