思路:二叉树的中序遍历是有序的!!!那就好搞了啊,回顾二叉树的中序遍历,栈的写法,照搬就好了。
先把所有左节点丢到栈中,获取最小值时弹栈,然后将指针指向其右节点,入栈,如果右节点有左子节点,再全部入栈。
# 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 = []
while root:
self.stack.append(root)
root = root.left
def next(self):
"""
@return the next smallest number
:rtype: int
"""
top = self.stack.pop()
node = top.right
while node:
self.stack.append(node)
node = node.left
return top.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.stack != []
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
嗯,栈和二叉树先这样,明天想写点 dp 和贪心的了。
网友评论