首页 > 其他 > 详细

173. Binary Search Tree Iterator

时间:2016-07-08 06:45:40      阅读:271      评论:0      收藏:0      [点我收藏+]

建一个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 }

 

173. Binary Search Tree Iterator

原文:http://www.cnblogs.com/warmland/p/5652093.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!