Swift solution - Stack


  • 0
    class BSTIterator {
        var stack = [TreeNode]()
        
        init(_ root: TreeNode?) {
            pushAll(root)
        }
        
        func hasNext() -> Bool {
            return !self.stack.isEmpty
        }
        
        func nex() -> Int {
            let node = self.stack.removeLast()
            pushAll(node.right)
            return node.val
        }
        
        fileprivate func pushAll(_ root: TreeNode?) {
            var root = root
            
            while root != nil {
                self.stack.append(root!)
                root = root?.left
            }
        }
    }
    

Log in to reply
 

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