题目:
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
代码:
- 解法一
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//使用栈进行实现
class BSTIterator {
Stack<TreeNode> stack=new Stack<>();
public BSTIterator(TreeNode root) {
TreeNode cur=root;
while(cur!=null){ //先将根节点和最左边子树全部进栈
stack.push(cur); //当前左子树进栈
cur=cur.left