I am a big fan of using C++ vector class


  • 0
    T
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    private:
        TreeNode *node;
        vector<TreeNode*> leftMostNodes;
    public:
        BSTIterator(TreeNode *root) {
            node = root;
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            while(node)
            {
                leftMostNodes.push_back(node);
                node = node->left;
            }
            if(leftMostNodes.size() == 0)
                return false;
            else
                return true;
        }
    
        /** @return the next smallest number */
        int next() {
            node = leftMostNodes.back();
            leftMostNodes.pop_back();
            int value = node->val;
            node = node->right;
            return value;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.