Ruby Solution


  • 0
    M
    class BSTIterator
        def initialize(root)
            @stack = []
            push_all_left(root)
        end
        
        def push_all_left(node)
            while node
                @stack << node
                node = node.left
            end
        end
    
        def has_next
            !@stack.empty?
        end
    
        def next
            node = @stack.pop
            push_all_left(node.right)
            node.val
        end
    end
    

Log in to reply
 

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