码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator

时间:2016-07-07 15:43:56      阅读:160      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!