My solution using Generator in JavaScript(or other languag)


  • 0
    X

    You can use the ES6's generator in creative way!!
    The code is easy, Python or other language which supports using generator in recursive way should also be done easy too!!

    /**
     * Definition for binary tree
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    
    /**
     * @constructor
     * @param {TreeNode} root - root of the binary search tree
     */
    var BSTIterator = function(root) {
        this.generator = generator(root)
        this._next = this.generator.next()
        function * generator(root) {
            if (root) {
                yield * generator(root.left)
                yield root.val
                yield * generator(root.right)
            }
        }
    };
    
    
    /**
     * @this BSTIterator
     * @returns {boolean} - whether we have a next smallest number
     */
    BSTIterator.prototype.hasNext = function() {
        return this._next.done === false
    };
    
    /**
     * @this BSTIterator
     * @returns {number} - the next smallest number
     */
    BSTIterator.prototype.next = function() {
        let value = this._next.value
        this._next = this.generator.next()
        return value
    };
    
    /**
     * Your BSTIterator will be called like this:
     * var i = new BSTIterator(root), a = [];
     * while (i.hasNext()) a.push(i.next());
    */
    

Log in to reply
 

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