实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next()
将返回二叉搜索树中的下一个最小的数。
示例:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
提示:
next()
和hasNext()
操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。- 你可以假设
next()
调用总是有效的,也就是说,当调用next()
时,BST 中至少存在一个下一个最小的数。
第一种思路:
利用BST的性质:BST的中序遍历为升序数组。
所以直接在init里用中序遍历然后存进数组里就好了。
时间复杂度:next() 和 hasNext()为O(1)
空间复杂度:O(N)
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.res = list()
def inorder(node):
if not node:
return
inorder(node.left)
self.res.append(node.val)
inorder(node.right)
inorder(root)
self.index = 0
def next(self):
"""
@return the next smallest number
:rtype: int
"""
self.index += 1
# print self.index - 1, self.res
return self.res[self.index - 1]
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.index < len(self.res)
第二种思路:
利用一个stack来存。
pushLeft这个函数的功能是把 一个节点和它的左孩子以及左孩子的左孩子.... 压入栈。
时间复杂度:next() 和 hasNext()为O(1)
空间复杂度:O(h)
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.pushLeft(root)
def next(self):
"""
@return the next smallest number
:rtype: int
"""
popedNode = self.stack.pop()
self.pushLeft(popedNode.right)
return popedNode.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return len(self.stack) != 0
def pushLeft(self, node):
while(node):
self.stack.append(node)
node = node.left
第三种思路:
类似二叉树的迭代法实现中序遍历。
时间复杂度:next() 和 hasNext()为O(1)
空间复杂度:O(h)
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.cur = root
def next(self):
"""
@return the next smallest number
:rtype: int
"""
while self.cur or self.stack:
if self.cur:
self.stack.append(self.cur)
self.cur = self.cur.left
else:
self.cur = self.stack.pop()
res = self.cur.val
self.cur = self.cur.right
return res
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.cur or self.stack