版权声明:原创部分都是自己总结的,如果转载请指明出处。觉得有帮助的老铁,请双击666! https://blog.csdn.net/qq_36387683/article/details/82529536
86. 二叉查找树迭代器
设计实现一个带有下列属性的二叉查找树的迭代器:
- 元素按照递增的顺序被访问(比如中序遍历)
next()
和hasNext()
的询问操作要求均摊时间复杂度是O(1)
样例
对于下列二叉查找树,使用迭代器进行中序遍历的结果为 [1, 6, 10, 11, 12]
10
/ \
1 11
\ \
6 12
挑战
额外空间复杂度是O(h),其中h是这棵树的高度
Super Star:使用O(1)的额外空间复杂度
解题思路:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
Example of iterate a tree:
iterator = BSTIterator(root)
while iterator.hasNext():
node = iterator.next()
do something for node
"""
class BSTIterator:
"""
@param: root: The root of binary tree.
"""
def __init__(self, root):
# do intialization if necessary
#维护一个栈
self.stack = []
self.cur = root
"""
@return: True if there has next node, or false
"""
def hasNext(self, ):
# write your code here
return self.cur is not None or len(self.stack) > 0
"""
@return: return next node
"""
def next(self, ):
# write your code here
#如果当前结点不为空,就添加结点,并寻找最左结点
while self.cur is not None:
self.stack.append(self.cur)
self.cur = self.cur.left
#弹出最新加入的,也就是当前最小的值
self.cur = self.stack.pop()
nxt = self.cur
#然后将当前结点赋值为右结点,方便下一轮判断
self.cur = self.cur.right
return nxt