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

【leetcode】Binary Search Tree Iterator

时间:2015-05-12 00:03:17      阅读:122      评论: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.

 

 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 };

 

【leetcode】Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4496005.html

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