Tuesday, August 25, 2015

Leetcode 173. Binary Search Tree Iterator

https://leetcode.com/problems/binary-search-tree-iterator/

The iterator consists of a tree and a stack. For BST, the smallest number is the most left node.

Solution:
# T:O(1) S:O(h)
class BSTIterator:
    # @param root, a binary search tree's root node
    def __init__(self, root):
        self.stack = []
        self.cur = root

    # @return a boolean, whether we have a next smallest number
    def hasNext(self):
        return self.stack or self.cur

    # @return an integer, the next smallest number
    def next(self):
        while self.cur:
            self.stack.append(self.cur)
            self.cur = self.cur.left
        
        self.cur = self.stack.pop()
        node = self.cur
        self.cur = self.cur.right
        
        return node.val
Run Time: 140 ms

No comments:

Post a Comment