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.

 

Analyse: Inorder traversal of BST. 

Runtime: 28ms.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class BSTIterator {
11 public:
12     BSTIterator(TreeNode *root) {
13         inorder(root);
14     }
15 
16     /** @return whether we have a next smallest number */
17     bool hasNext() {
18         return !qu.empty();
19     }
20 
21     /** @return the next smallest number */
22     int next() {
23         int nextSmallest = qu.front();
24         qu.pop();
25         return nextSmallest;
26     }
27 private:
28     queue<int> qu;
29     
30     void inorder(TreeNode* root) {
31         if(!root) return;
32         
33         inorder(root->left);
34         qu.push(root->val);
35         inorder(root->right);
36     }
37 };
38 
39 /**
40  * Your BSTIterator will be called like this:
41  * BSTIterator i = BSTIterator(root);
42  * while (i.hasNext()) cout << i.next();
43  */

 

posted @ 2016-08-10 05:57  amazingzoe  阅读(132)  评论(0编辑  收藏  举报