# Kth Smallest Element in a BST

1. 问题

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.

2. 解答
class Solution1 {
public:

int kthSmallest(TreeNode* root, int k) {
inorderTraversal(root);
return res[k-1];
}

void inorderTraversal(TreeNode* root)
{
if(root)
{

inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
}
//   return res;
}

private:
vector<int> res;
};

class Solution2 {
public:

int kthSmallest(TreeNode* root, int k)
{
vector<int> res;
int sum=0;
vector<TreeNode *> f1;

while(root)
{
f1.push_back(root);
root=root->left;
}
TreeNode *temp;
while(!f1.empty() )
{
temp=f1.back();

res.push_back(temp->val);
sum++;
if(sum==k) return temp->val;
f1.pop_back();

if(temp->right!=NULL)
{
TreeNode *f=temp->right;
while(f)
{
f1.push_back(f);
f=f->left;
}
}

}
}
};

class Solution {
public:

int kthSmallest(TreeNode* root, int k)
{
int sum=0;
stack<TreeNode *> f1;
// inorder
while(root || !f1.empty())
{
while(root)
{
f1.push(root);
root=root->left;
}
if(!f1.empty())
{
TreeNode *temp;
temp=f1.top();
sum++;
if(sum==k) return temp->val;
f1.pop();

if(temp->right!=NULL)
{
root=temp->right;
}
}

}
}

};

• 本文已收录于以下专栏：

举报原因： 您举报文章：Kth Smallest Element in a BST 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)