JavaScript solution using a stack (accepted)


  • 0
    T
    'use strict'
    class BSTIterator {
        constructor(root) {
            this.stack = []
            this._addWorkForNode(root)
        }
        hasNext() {
            return this.stack.length !== 0
        }
        _addWorkForNode(node) {
            let curNode = node
            while(curNode) {
                this.stack.push(curNode)
                curNode = curNode.left
            }
        }
        next() {
            const node = this.stack.pop()
            this._addWorkForNode(node.right)
            return node.val
        }
    }
    

    I can add more description on request.


Log in to reply
 

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