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.

 

 1 class BSTIterator {
 2     stack<TreeNode *>s;
 3 public:
 4     BSTIterator(TreeNode *root) {
 5         while(!s.empty())
 6             s.pop();
 7         while(root)
 8         {
 9             s.push(root);
10             root=root->left;
11         }
12     }
13 
14     /** @return whether we have a next smallest number */
15     bool hasNext() {
16         return !s.empty();
17     }
18 
19     /** @return the next smallest number */
20     int next() {
21         TreeNode *tmp=s.top();
22         s.pop();
23         int ret=tmp->val;
24         tmp=tmp->right;
25         while(tmp)
26         {
27             s.push(tmp);
28             tmp=tmp->left;
29         }
30 
31         return ret;
32     }
33 };

 

posted on 2015-05-11 23:02  黄瓜小肥皂  阅读(126)  评论(0编辑  收藏  举报