这道题相当用 DFS 求解,用一个 stack 来维护一个最小值,就是一直把最左边的结点装到 stack 里面,用 stack pop 下一个最小值出来
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassBSTIterator {privateStack<TreeNode> stack =newStack<TreeNode>();privateTreeNode curr;publicBSTIterator(TreeNode root) {this.curr= root; } /** @return whether we have a next smallest number */publicbooleanhasNext() {return curr !=null||!stack.isEmpty(); } /** @return the next smallest number */publicintnext() {while (curr !=null) {stack.push(curr); curr =curr.left; }TreeNode node =stack.pop(); curr =node.right;returnnode.val; }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */