My Simple Python solution

  • 0
    class BSTIterator:
    # @param root, a binary search tree's root node
    def __init__(self, root):
        self.root = root
    # @return a boolean, whether we have a next smallest number
    def hasNext(self):
        return self.root != None
    # @return an integer, the next smallest number
    def next(self):
        self.min = None
        self.root = self.findSmallest(self.root)
        return self.min
    def findSmallest(self, root):
        if root.left:
            root.left = self.findSmallest(root.left)
            return root
            self.min = root.val
            return root.right

  • 0

    Is the time O(1)?
    And is the tree destroyed after searching?

Log in to reply

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