仅供自己学习记录
LeetCode刷题日记2021-3-28
链接:https://leetcode-cn.com/problems/binary-search-tree-iterator
题目描述:
实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器:
BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。
boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false 。
int next()将指针向右移动,然后返回指针处的数字。
注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。
示例:
输入
[“BSTIterator”, “next”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
输出
[null, 3, 7, true, 9, true, 15, true, 20, false]
解释
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // 返回 3
bSTIterator.next(); // 返回 7
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 9
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 15
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 20
bSTIterator.hasNext(); // 返回 False
输入
[“BSTIterator”, “next”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
输出
[null, 3, 7, true, 9, true, 15, true, 20, false]
解释
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // 返回 3
bSTIterator.next(); // 返回 7
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 9
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 15
bSTIterator.hasNext(); // 返回 True
bSTIterator.next(); // 返回 20
bSTIterator.hasNext(); // 返回 False
题目解释:
输入一个二叉树
输出一个二叉树迭代器
next()输出当前指针指向的元素值
hasNext() 返回值为bool类型如果指针右侧有数字则返回True 无数字返回False
解题思路
用栈存储二叉树
并且每次只存储当前节点的左子树到栈中,这样pop的顺序就会大于父节点
当pop出当前节点以后 如果当前节点有右子树 则将右子树按照一个较小的根节点来存储到栈中
题解代码
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
#定义一个栈存储当前根节点
self.stack = []
self.in_order(root)
def in_order(self, node):
#当前节点存在时存储并且查找其左子树节点如果有也存储
while node:
self.stack.append(node)
node = node.left
def next(self):
"""
@return the next smallest number
:rtype: int
"""
#弹出当前栈顶元素 实现中序遍历 并且判断该节点有无右子树 如果有进行存储
node = self.stack.pop()
if node.right:
self.in_order(node.right)
return node.val
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
##判断当前栈是否为空 如果为空则说明迭代器指针右侧无数字
##如果不为空则说明右侧有数字
return bool(self.stack)
思路来源:https://leetcode-cn.com/problems/binary-search-tree-iterator/solution/python-zhan-by-qubenhao-dciu/