leetcode 173. Binary Search Tree Iterator
class BSTIterator { private Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); while(root != null){ stack.push(root); root = root.left; } } /** @return the next smallest number */ public int next() { TreeNode cur = stack.pop(); TreeNode tmp = cur; if(tmp != null){ tmp = tmp.right; while(tmp != null){ stack.push(tmp); tmp = tmp.left; } } return cur.val; } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } }