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

Binary Search Tree Iterator

时间:2015-08-05 23:55:07      阅读:121      评论: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.

采用中序遍历将节点压入栈中,由于要求存储空间为O(h),因此不能在一开始将所有节点全部压入,只是压入最左边一列。当取出一个节点时,压入其右子节点的所有左节点。

 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 private:
12     stack <TreeNode*> stk;
13     int minres;
14 public:
15     BSTIterator(TreeNode *root) {
16         while(root)
17         {
18             stk.push(root);
19             root=root->left;
20         }
21     }
22 
23     /** @return whether we have a next smallest number */
24     bool hasNext() {
25         if(stk.empty())
26             return false;
27         TreeNode* top;
28         top=stk.top();
29         minres=top->val;
30         stk.pop();
31         TreeNode* cur=top->right;
32         if(cur)
33         {
34             stk.push(cur);
35             cur=cur->left;
36             while(cur)
37             {
38                 stk.push(cur);
39                 cur=cur->left;
40             }
41         }
42         return true;
43     }
44 
45     /** @return the next smallest number */
46     int next() {
47         return minres;
48     }
49 };
50 
51 /**
52  * Your BSTIterator will be called like this:
53  * BSTIterator i = BSTIterator(root);
54  * while (i.hasNext()) cout << i.next();
55  */

 

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/zl1991/p/4705921.html

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