C++ solution using true iterators


  • 0
    A
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    public:
        BSTIterator(TreeNode *root) : left(nullptr), right(nullptr) {
            current = root;
            if (root == nullptr) {
                return;
            }
            
            if (current->left != nullptr) {
                left = new BSTIterator(current->left);
            }
            
            if (current->right != nullptr) {
                right = new BSTIterator(current->right);
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return ((current != nullptr) || (left != nullptr) || (right != nullptr));
        }
    
        /** @return the next smallest number */
        int next() {
            int value;
            if (left != nullptr) {
                value = getChildValue(left);
                
            } else if (current != nullptr) {
                value = current->val;
                current = nullptr;
                
            } else if (right != nullptr) {
                value = getChildValue(right);
            }
            
            return value;
        }
    
    protected:
        int getChildValue(BSTIterator *&child) {
            int value = child->next();
            if (!child->hasNext()) {
                delete child;
                child = nullptr;
            }
            
            return value;
        }
    
    protected:
        
        TreeNode *current;
        BSTIterator *left;
        BSTIterator *right;
    };
    
    /**
     * 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.