Binary Search Tree Iterator using DFS style approach and a stack.


  • 0
    H
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
    
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
    
    struct SE //StackElement
    {
    TreeNode* n;
    bool leftVisited;
        SE(TreeNode *iN, bool i_leftVisited) { n=iN; leftVisited = i_leftVisited;}
    };
    
    class BSTIterator {
        
        stack<SE> s;
        
    public:
        BSTIterator(TreeNode *root) {
            if (root) s.push(SE(root, false));
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            
            if (s.size()==0)
                return false;
            
            while(!s.top().leftVisited && s.top().n->left != nullptr)
            {            
                s.top().leftVisited = true;
                s.push(SE(s.top().n->left, false));
            }
            
            return true;
        }
    
        /** @return the next smallest number */
        int next() {
            
            TreeNode *n = s.top().n;
            
            s.pop();
            
            if (n->right) s.push(SE(n->right, false));
            
            return n->val;
        }
    };
    
    

Log in to reply
 

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