LeetCode 230 Kth Smallest Element in a BST
思路
中序遍历
代码
迭代
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> stk;
TreeNode *cur = root;
while (cur || !stk.empty()) {
while (cur) {
stk.push(cur);
cur = cur->left;
}
cur = stk.top();
stk.pop();
if (!--k)
return cur->val;
cur = cur->right;
}
return cur->val;
}
};
递归
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
vector<int> ans;
inorder(root, ans);
return ans[k-1];
}
void inorder(TreeNode *root, vector<int> &ans) {
if (!root) return ;
inorder(root->left, ans);
ans.push_back(root->val);
inorder(root->right, ans);
}
};