173. 二叉搜索树迭代器

 

Q:

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

示例:

BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false

提示:

next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。

A:

要求内存使用O(H),那么就不能保存中序序列了。考虑用栈,栈最多存储h个元素(即一条左链)。

c++:

 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 class BSTIterator {
11     stack<TreeNode*>sta;
12 public:
13     BSTIterator(TreeNode* root) {
14         while(root){
15             sta.push(root);
16             root=root->left;
17         }
18     }
19     
20     /** @return the next smallest number */
21     int next() {
22         auto p=sta.top();
23         int res=p->val;
24         sta.pop();
25         p=p->right;
26         while(p){
27             sta.push(p);
28             p=p->left;
29         }
30         return res;
31     }
32     
33     /** @return whether we have a next smallest number */
34     bool hasNext() {
35         return not sta.empty();
36     }
37 };
38 
39 /**
40  * Your BSTIterator object will be instantiated and called as such:
41  * BSTIterator* obj = new BSTIterator(root);
42  * int param_1 = obj->next();
43  * bool param_2 = obj->hasNext();
44  */

 

python:

 1 class BSTIterator:
 2 
 3     def __init__(self, root: TreeNode):
 4         self.stack=[]
 5         while root:
 6             self.stack.append(root)
 7             root=root.left
 8 
 9     def next(self) -> int:
10         """
11         @return the next smallest number
12         """
13         y=self.stack[-1].val
14         x=self.stack[-1].right
15         del self.stack[-1]
16         while x:
17             self.stack.append(x)
18             x=x.left
19         return y
20 
21     def hasNext(self) -> bool:
22         """
23         @return whether we have a next smallest number
24         """
25         if not self.stack:
26             return False
27         return True

 

posted @ 2019-08-16 19:50  NeoZy  阅读(106)  评论(0编辑  收藏  举报