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.

思路一:

使用inorder traversal把tree转化为arraylist。

 1 public class BSTIterator {
 2         
 3         ArrayList<TreeNode> list;
 4         int index;
 5 
 6         public BSTIterator(TreeNode root) {
 7             list  = new ArrayList<TreeNode>();
 8             iterator(root, list);
 9             index = 0;
10         }
11         
12         public void iterator(TreeNode root, ArrayList<TreeNode> list) {
13             if(root != null) {
14                 iterator(root.left, list);
15                 list.add(root);
16                 iterator(root.right, list);
17             }
18         }
19 
20         /** @return whether we have a next smallest number */
21         public boolean hasNext() {
22             if(index < list.size()) {
23                 return true;
24             }
25             return false;
26         }
27 
28         /** @return the next smallest number */
29         public int next() {
30             return list.get(index++).val;
31         }
32     }

 思路二:

将iterator的实现改为迭代。

 1 public void iterator(TreeNode root, ArrayList<TreeNode> list) {
 2             Stack<TreeNode> stack = new Stack<TreeNode>();
 3             TreeNode node = root;
 4             while(!stack.isEmpty() || node != null) {
 5                 if(node != null) {
 6                     stack.push(node);
 7                     node = node.left;
 8                 } else {
 9                     node  = stack.pop();
10                     list.add(node);
11                     node = node.right;
12                 }
13             }
14         }

 

posted on 2015-03-24 15:27  绿树荫  阅读(125)  评论(0编辑  收藏  举报

导航