/* * 173. Binary Search Tree Iterator * 2016-6-4 by Mingyang * 就是一个典型的DFS,保证在constructor的时候就需要保持一个stack的情况,push进去最小的那个值 * 每次取了值以后注意不要忘了继续往stack里面push * return the next smallest number in the BST是值的是从零开始起return,一个一个的return */ class BSTIterator { Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<TreeNode>(); while (root != null) { stack.push(root); root = root.left; } } public boolean hasNext() { return !stack.isEmpty(); } public int next() { TreeNode node = stack.pop(); int result = node.val; if (node.right != null) { node = node.right; while (node != null) { stack.push(node); node = node.left; } } return result; } } //下面就是自己写的一次过的代码,多用了一个queue,一次性的把所有的都存起来了,一个一个取方便 class BSTIterator1 { Stack<TreeNode> stack=new Stack<TreeNode>(); Queue<TreeNode> queue=new LinkedList<TreeNode>(); public BSTIterator1(TreeNode root) { TreeNode p=root; while(p!=null||stack.size()!=0){ if(p!=null){ stack.push(p); p=p.left; }else{ TreeNode q=stack.pop(); queue.add(q); p=q.right; } } } /** @return whether we have a next smallest number */ public boolean hasNext() { if(queue.size()>0) return true; else return false; } /** @return the next smallest number */ public int next() { return queue.remove().val; } }