1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 public class BSTIterator { 12 private Stack<TreeNode> stack; 13 14 private void initialNode(TreeNode root) { 15 while (root != null) { 16 stack.push(root); 17 root = root.left; 18 } 19 } 20 public BSTIterator(TreeNode root) { 21 stack = new Stack<>(); 22 initialNode(root); 23 } 24 25 /** @return whether we have a next smallest number */ 26 public boolean hasNext() { 27 return stack.size() > 0; 28 } 29 30 /** @return the next smallest number */ 31 public int next() { 32 TreeNode root = stack.pop(); 33 if (root.right != null) { 34 initialNode(root.right); 35 } 36 return root.val; 37 } 38 } 39 40 /** 41 * Your BSTIterator will be called like this: 42 * BSTIterator i = new BSTIterator(root); 43 * while (i.hasNext()) v[f()] = i.next(); 44 */