class BSTIterator(object):
def __init__(self, root):
self.stack = []
while root:
self.stack.append(root)
root = root.left
def next(self):
cur = self.stack.pop()
node = cur.right
while node:
self.stack.append(node)
node = node.left
return cur.val
def hasNext(self):
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
栈,中等,每日一题
展开二叉树的想法很简单,但是不符合代码“迭代器不修改源数据”的规范。
其实就是模拟一个中序遍历的过程
https://leetcode-cn.com/problems/binary-search-tree-iterator/
题解:https://leetcode-cn.com/problems/binary-search-tree-iterator/solution/fu-xue-ming-zhu-dan-diao-zhan-die-dai-la-dkrm/