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

Binary Search Tree Iterator

时间:2015-03-12 16:45:35      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

iterative inorder traveral 的变型。

 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 // iterative inorder traveral change
12 public class BSTIterator {
13     LinkedList<TreeNode> stack;
14     boolean flg;
15     TreeNode tmp;
16     public BSTIterator(TreeNode root) {
17         stack = new LinkedList<TreeNode> ();
18         tmp = root;
19         flg = (root != null);
20     }
21 
22     /** @return whether we have a next smallest number */
23     public boolean hasNext() {
24         return flg && !(stack.isEmpty() && tmp == null);
25     }
26 
27     /** @return the next smallest number */
28     public int next() {
29         while(true){
30             if(tmp != null){
31                 stack.push(tmp);
32                 tmp = tmp.left;
33             }else{
34                 TreeNode result = stack.pop();
35                 tmp = result.right;
36                 return result.val;
37             }
38         }
39     }
40 }
41 
42 /**
43  * Your BSTIterator will be called like this:
44  * BSTIterator i = new BSTIterator(root);
45  * while (i.hasNext()) v[f()] = i.next();
46  */

 

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/reynold-lei/p/4332691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!