您的位置:首页 > 其它

【LEETCODE】173-Binary Search Tree Iterator

2015-11-05 14:48 447 查看
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and
hasNext() should run in average O(1) time and uses O(h) memory, where
h is the height of the tree.

参考: https://github.com/kamyu104/LeetCode/blob/master/Python/binary-search-tree-iterator.py
# 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的轨迹
self.cur=root                      #从root起,先走左child,一直到leave层

def hasNext(self):
"""
:rtype: bool
"""
return self.stack or self.cur      #当stack和cur都为空的时候,是已经从leave到达最right的root了

def next(self):
"""
:rtype: int
"""
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                    #append到v上

# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: