1. 题目描述 2. 解法1 扁平化法 思路: 首先将二叉搜索树中元素通过dfs搜索遍历所有元素,保存至数组。定义一个指针实现移动取值;通过判断指针是否在数组索引区间来判断是否存在下一个值代码: # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTIterator: def __init__(self, root: TreeNode): self.id = -1 self.elements = [] # 升序保存元素 self.in_order(root) # dfs搜索二叉树 def in_order(self, root): if root is None: return self.in_order(root.left) self.elements.append(root.val) self.in_order(root.right) def next(self) -> int: # 移位取值 self.id += 1 return self.elements[self.id] def hasNext(self) -> bool: num = len(self.elements) if self.id+1 < num: return True return False