HasNext() and Next Both using time O(1) and space O(1) !!!


  • -7
    W
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        vector<int> values ;
        int pointer ;
        void inorder(TreeNode *root)
        {
            if (root)
            {
                inorder(root->left);
                values.push_back(root->val);
                inorder(root->right);
            }
        }
        BSTIterator(TreeNode *root)
        {
            inorder(root);
            pointer = 0 ;
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return pointer < values.size() ;
        }
    
        /** @return the next smallest number */
        int next() {
            return values[pointer++];
        }
        };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */

  • 2
    C

    your values can't as long as the tree


Log in to reply
 

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