码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator ***

时间:2015-08-03 13:01:20      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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: find the next smallest number in the BST and realize the iteration process. The same as inorder traversal.

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     stack<TreeNode* > stk;
13     BSTIterator(TreeNode *root) {
14         while(root){
15             stk.push(root);
16             root = root->left;
17         }
18     }
19 
20     /** @return whether we have a next smallest number */
21     bool hasNext() {
22         return !stk.empty();
23     }
24 
25     /** @return the next smallest number */
26     int next() {
27         TreeNode* temp = stk.top();
28         stk.pop();
29         int nextMin = temp->val;
30         temp = temp->right;
31         while(temp){
32             stk.push(temp);
33             temp = temp->left;
34         }
35         return nextMin;
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  */

 

Binary Search Tree Iterator ***

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4699006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!