首页 > 其他 > 详细

173. 二叉搜索树迭代器

时间:2020-03-24 14:49:24      阅读:60      评论:0      收藏:0      [点我收藏+]
 1 /**
 2  * Definition for a binary tree node.
 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 //中序遍历的拆分
11 class BSTIterator 
12 {
13     stack<TreeNode*> s;
14     TreeNode* head;
15 public:
16     BSTIterator(TreeNode* root) 
17     {
18         head = root;
19         while(head != NULL)
20         {
21             s.push(head);
22             head = head->left;
23         }
24     }
25     
26     /** @return the next smallest number */
27     int next() 
28     {
29         TreeNode* p = s.top();
30         s.pop();
31         int temp = p->val;
32         p = p->right;
33         while(p)
34         {
35             s.push(p);
36             p = p->left;
37         }
38         return temp;
39     }
40     
41     /** @return whether we have a next smallest number */
42     bool hasNext() 
43     {
44         return !s.empty();
45     }
46 };
47 
48 /**
49  * Your BSTIterator object will be instantiated and called as such:
50  * BSTIterator* obj = new BSTIterator(root);
51  * int param_1 = obj->next();
52  * bool param_2 = obj->hasNext();
53  */

 

173. 二叉搜索树迭代器

原文:https://www.cnblogs.com/yuhong1103/p/12558320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!