230. 二叉搜索树中第K小的元素(c++)

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> s;
        int num = 0;
        TreeNode *cur = root;
        while(!s.empty()|| cur)
        {
            if(cur)
            {
                s.push(cur);
                cur = cur->left;
            }
            else
            {
                cur = s.top();
                s.pop();
                num++;
                if(num == k)
                    return cur->val;
                cur = cur->right;
            }
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/one-think/p/12673569.html