可以把中序遍历的过程融入到next函数中,可以更快,下边的做法是先遍历完,比较垃圾
//记录节点值 Queue<Integer> vals = new LinkedList<>(); public BSTIterator(TreeNode root) { //构造函数不能主动调用所以不能递归,迭代中序遍历得到升序list Stack<TreeNode> stack = new Stack<>(); while (!stack.isEmpty()||root!=null) { if (root!=null) { stack.push(root); root = root.left; } else { root = stack.pop(); vals.offer(root.val); root = root.right; } } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !vals.isEmpty(); } /** @return the next smallest number */ public int next() { return vals.poll(); }