Leetcode 173 Solution

This article provides solution to leetcode question 173 (binary-search-tree-iterator)

https://leetcode.com/problems/binary-search-tree-iterator

Solution

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    vector<TreeNode*> s;

public:
    BSTIterator(TreeNode *root) {
        auto p = root;
        while (p)
        {
            s.push_back(p);
            p = p->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return s.empty() == false;
    }

    /** @return the next smallest number */
    int next() {
        auto p = s.back();
        int val = p->val;
        s.pop_back();

        if (p->right)
        {
            p = p->right;

            while (p)
            {
                s.push_back(p);
                p = p->left;
            }
        }

        return val;
    }
};

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