173. Binary Search Tree Iterator

建一个stack,最末的元素始终是最小的那个。

所以对于初始化,存到最左下角的那个节点。

对于找到next,就是存到,当前节点的右子节点的最左下角(如果有的话)。

 1 public class BSTIterator {
 2     Stack<TreeNode> stack;
 3     
 4     public BSTIterator(TreeNode root) {
 5         stack = new Stack<TreeNode>();
 6         TreeNode cur = root;
 7         while(cur != null) {
 8             stack.push(cur);
 9             cur = cur.left;
10         }
11     }
12 
13     /** @return whether we have a next smallest number */
14     public boolean hasNext() {
15         return !stack.isEmpty();
16     }
17 
18     /** @return the next smallest number */
19     public int next() {
20         TreeNode cur = stack.pop();
21         int next = cur.val;
22         cur = cur.right;
23         while(cur != null) {
24             stack.push(cur);
25             cur = cur.left;
26         }
27         return next;
28     }
29 }

 

posted @ 2016-07-08 05:13  warmland  阅读(153)  评论(0编辑  收藏  举报