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.valRun Time: 140 ms
No comments:
Post a Comment