[LeetCode]Binary Search Tree Iterator

本文介绍如何使用栈实现二叉搜索树的迭代器,能够以中序遍历的方式输出树中的节点,并且在O(1)平均时间内完成next()和hasNext()操作。

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

题意差不多就是将BST按中序非递归输出。当然stack。

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

 

转载于:https://www.cnblogs.com/Sean-le/p/4814718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值