Clear JavaScript solution using stack


  • 0
    class BSTIterator {
        constructor(root) {
            this.greaterParents = [];
            this.walkLeftFrom(root);
        }
        
        walkLeftFrom(node) {
            while (node) {
                this.greaterParents.push(node);
                node = node.left;
            }
        }
        
        hasNext() {
            return !!(this.greaterParents.length || this.curr && this.curr.right);
        }
        
        next() {
            if (this.curr && this.curr.right) {
                this.walkLeftFrom(this.curr.right);
            }
            this.curr = this.greaterParents.pop();
            return this.curr.val;
        }
    }
    

Log in to reply
 

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