Discription:
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.
Solution:
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> stack;
while (root || !stack.empty()){
if (root){
stack.push(root);
root = root->left;
}
else{
root = stack.top();
stack.pop();
if (--k == 0)
break;
root = root->right;
}
}
return root->val;
}
};
GitHub-Leetcode:https://github.com/wenwu313/LeetCode
参考:https://leetcode.com/problems/validate-binary-search-tree/?tab=Solutions