s4553711
4/26/2017 - 2:04 PM

173.cpp

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    stack<TreeNode*> stk;
    int min;
    BSTIterator(TreeNode *root) {
        while(root) {
            stk.push(root);
            root = root->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if (!stk.empty()) {
            TreeNode*  tmp = stk.top();
            stk.pop();
            min = tmp->val;
            TreeNode* cur = tmp->right;
            if (cur) {
                stk.push(cur);
                cur = cur->left;
                while(cur) {
                    stk.push(cur);
                    cur = cur->left;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    /** @return the next smallest number */
    int next() {
        return min;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */