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.

思路:

通过中序遍历将结果保存到一个队列queue中,hasNext()判断queue是否为空,getNext()返回队列头部元素即可

 1 public class BSTIterator {
 2     private Queue<Integer> queueOfInOrder = new LinkedList<Integer>();            //保存中序遍历得到的队列
 3     public BSTIterator(TreeNode root) {
 4         InOrder(root);                                                            //中序遍历树,得到中序遍历结点队列
 5     }
 6 
 7     /** @return whether we have a next smallest number */
 8     public boolean hasNext() {
 9         if(queueOfInOrder.isEmpty())
10             return false;                                                        //队列为空,说明已经最后一个元素
11         return true;
12     }
13 
14     /** @return the next smallest number */
15     public int next() {
16         Integer headOfQueue = queueOfInOrder.poll();
17         
18         return headOfQueue;
19     }
20     
21     /**
22      * 中序遍历树
23      */
24     private void InOrder(TreeNode root){
25         if(null != root){
26             InOrder(root.left);
27             queueOfInOrder.add(root.val);
28             InOrder(root.right);
29         }
30     }
31 }
原文地址:https://www.cnblogs.com/luckygxf/p/4196732.html