方法一:递归-中序遍历
class Solution {
private:
vector<int> vc; //保存中序遍历结果
void inorder(TreeNode* root){
if(!root)
return;
inorder(root->left);
vc.push_back(root->val);
inorder(root->right);
}
public:
int kthSmallest(TreeNode* root, int k) {
inorder(root);
return vc[k-1];
}
};
方法二:递归-中序遍历,提前结束
class Solution {
private:
int cnt;
int res;
void inorder(TreeNode* root){
if(!root || !cnt) //遍历访问结点数达到返回
return;
inorder(root->left);
if(--cnt==0)
res=root->val;
inorder(root->right);
}
public:
int kthSmallest(TreeNode* root, int k) {
cnt=k;
inorder(root);
return res;
}
};
方法三:迭代法-中序遍历,提前结束
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
int cnt=0;
while(!st.empty() || root){
while(root){
st.push(root);
root=root->left;
}
TreeNode* top=st.top();
st.pop();
if(++cnt==k)
return top->val;
root=top->right;
}
return -1;
}
};