首页 > 其他 > 详细

Binary Search Tree Iterator

时间:2016-07-07 15:41:48      阅读:213      评论:0      收藏:0      [点我收藏+]
 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  */

 

Binary Search Tree Iterator

原文:http://www.cnblogs.com/shuashuashua/p/5650327.html

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