173. Binary Search Tree Iterator
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
cur = root
while cur is not None:
self.stack.append(cur)
if cur.left:
cur = cur.left
else:
break
# print("len(self.stack) %s" %(len(self.stack)))
def hasNext(self):
"""
:rtype: bool
"""
return self.stack
def next(self):
"""
:rtype: int
"""
if not self.stack: return None
ans = self.stack.pop()
cur = ans
# check whether there is a right child, if there is, traverse towards the leftmost
# of the right child.
if cur.right:
cur = cur.right
while cur:
self.stack.append(cur)
if cur.left:
cur = cur.left
else:
break
return ans.val
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())Last updated
Was this helpful?