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.
class Solution {You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
public:
void pushLefts(stack<TreeNode*>& s, TreeNode* root)
{
while(root != NULL)
{
s.push(root);
root = root->left;
}
}
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> tmp;
pushLefts(tmp, root);
while (!tmp.empty())
{
TreeNode* cur = tmp.top();
tmp.pop();
if (k == 1)
{
return cur->val;
}
pushLefts(tmp, cur->right);
k--;
}
return -1;
}
};