Binary Search Tree Iterator

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  */

 

posted on 2015-03-12 15:58  Step-BY-Step  阅读(320)  评论(0编辑  收藏  举报

导航