173. Binary Search Tree Iterator
use stack to iteratively traverse binary tree in order
left, root, right
# 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=[]
self.cur=root
def hasNext(self):
"""
:rtype: bool
"""
return self.stack or self.cur
def next(self):
"""
:rtype: int
"""
while self.cur:
self.stack.append(self.cur)
self.cur=self.cur.left
node=self.stack.pop()
self.cur=node.right
return node.val
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
本文标题:173. Binary Search Tree Iterator
本文链接:https://www.haomeiwen.com/subject/uxtoettx.html
网友评论