My clear cpp code using stack


  • 1
    C
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) 
        {
            while(root)
            {
                nodeStack.push(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() 
        {
            return !nodeStack.empty();
        }
    
        /** @return the next smallest number */
        int next() 
        {
            TreeNode* node = nodeStack.top();
            nodeStack.pop();
            int num = node->val;
            
            node = node->right;
            while(node)
            {
                nodeStack.push(node);
                node = node->left;
            }
            
            return num;
        }
        
    private:
        std::stack<TreeNode*> nodeStack;
    };
    
    /**
     * 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.