Skip to content

Commit c570c1d

Browse files
committed
feat: add solutions to lc/lcof2 problem: Binary Search Tree Iterator
1 parent e70a181 commit c570c1d

File tree

13 files changed

+1179
-128
lines changed

13 files changed

+1179
-128
lines changed

lcof2/剑指 Offer II 055. 二叉搜索树迭代器/README.md

+354
Original file line numberDiff line numberDiff line change
@@ -73,22 +73,375 @@ bSTIterator.hasNext(); // 返回 False
7373

7474
<!-- 这里可写通用的实现逻辑 -->
7575

76+
**方法一:递归**
77+
78+
初始化数据时,递归中序遍历,将二叉搜索树每个结点的值保存在列表 `vals` 中。用 `cur` 指针记录外部即将遍历的位置,初始化为 0。
79+
80+
调用 `next()` 时,返回 `vals[cur]`,同时 `cur` 指针自增。调用 `hasNext()` 时,判断 `cur` 指针是否已经达到 `len(vals)` 个数,若是,说明已经遍历结束,返回 false,否则返回 true。
81+
82+
**方法二:栈迭代**
83+
84+
初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。
85+
86+
调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。
87+
7688
<!-- tabs:start -->
7789

7890
### **Python3**
7991

8092
<!-- 这里可写当前语言的特殊实现逻辑 -->
8193

8294
```python
95+
# Definition for a binary tree node.
96+
# class TreeNode:
97+
# def __init__(self, val=0, left=None, right=None):
98+
# self.val = val
99+
# self.left = left
100+
# self.right = right
101+
class BSTIterator:
102+
103+
def __init__(self, root: TreeNode):
104+
def inorder(root):
105+
if root:
106+
inorder(root.left)
107+
self.vals.append(root.val)
108+
inorder(root.right)
109+
110+
self.cur = 0
111+
self.vals = []
112+
inorder(root)
113+
114+
def next(self) -> int:
115+
res = self.vals[self.cur]
116+
self.cur += 1
117+
return res
118+
119+
def hasNext(self) -> bool:
120+
return self.cur < len(self.vals)
121+
122+
123+
# Your BSTIterator object will be instantiated and called as such:
124+
# obj = BSTIterator(root)
125+
# param_1 = obj.next()
126+
# param_2 = obj.hasNext()
127+
```
83128

129+
```python
130+
# Definition for a binary tree node.
131+
# class TreeNode:
132+
# def __init__(self, val=0, left=None, right=None):
133+
# self.val = val
134+
# self.left = left
135+
# self.right = right
136+
class BSTIterator:
137+
138+
def __init__(self, root: TreeNode):
139+
self.stack = []
140+
while root:
141+
self.stack.append(root)
142+
root = root.left
143+
144+
def next(self) -> int:
145+
cur = self.stack.pop()
146+
node = cur.right
147+
while node:
148+
self.stack.append(node)
149+
node = node.left
150+
return cur.val
151+
152+
def hasNext(self) -> bool:
153+
return len(self.stack) > 0
154+
155+
156+
# Your BSTIterator object will be instantiated and called as such:
157+
# obj = BSTIterator(root)
158+
# param_1 = obj.next()
159+
# param_2 = obj.hasNext()
84160
```
85161

86162
### **Java**
87163

88164
<!-- 这里可写当前语言的特殊实现逻辑 -->
89165

90166
```java
167+
/**
168+
* Definition for a binary tree node.
169+
* public class TreeNode {
170+
* int val;
171+
* TreeNode left;
172+
* TreeNode right;
173+
* TreeNode() {}
174+
* TreeNode(int val) { this.val = val; }
175+
* TreeNode(int val, TreeNode left, TreeNode right) {
176+
* this.val = val;
177+
* this.left = left;
178+
* this.right = right;
179+
* }
180+
* }
181+
*/
182+
class BSTIterator {
183+
private int cur = 0;
184+
private List<Integer> vals = new ArrayList<>();
185+
186+
public BSTIterator(TreeNode root) {
187+
inorder(root);
188+
}
189+
190+
public int next() {
191+
return vals.get(cur++);
192+
}
193+
194+
public boolean hasNext() {
195+
return cur < vals.size();
196+
}
197+
198+
private void inorder(TreeNode root) {
199+
if (root != null) {
200+
inorder(root.left);
201+
vals.add(root.val);
202+
inorder(root.right);
203+
}
204+
}
205+
}
206+
207+
/**
208+
* Your BSTIterator object will be instantiated and called as such:
209+
* BSTIterator obj = new BSTIterator(root);
210+
* int param_1 = obj.next();
211+
* boolean param_2 = obj.hasNext();
212+
*/
213+
```
91214

215+
```java
216+
/**
217+
* Definition for a binary tree node.
218+
* public class TreeNode {
219+
* int val;
220+
* TreeNode left;
221+
* TreeNode right;
222+
* TreeNode() {}
223+
* TreeNode(int val) { this.val = val; }
224+
* TreeNode(int val, TreeNode left, TreeNode right) {
225+
* this.val = val;
226+
* this.left = left;
227+
* this.right = right;
228+
* }
229+
* }
230+
*/
231+
class BSTIterator {
232+
private Deque<TreeNode> stack = new LinkedList<>();
233+
234+
public BSTIterator(TreeNode root) {
235+
for (; root != null; root = root.left) {
236+
stack.offerLast(root);
237+
}
238+
}
239+
240+
public int next() {
241+
TreeNode cur = stack.pollLast();
242+
for (TreeNode node = cur.right; node != null; node = node.left) {
243+
stack.offerLast(node);
244+
}
245+
return cur.val;
246+
}
247+
248+
public boolean hasNext() {
249+
return !stack.isEmpty();
250+
}
251+
}
252+
253+
/**
254+
* Your BSTIterator object will be instantiated and called as such:
255+
* BSTIterator obj = new BSTIterator(root);
256+
* int param_1 = obj.next();
257+
* boolean param_2 = obj.hasNext();
258+
*/
259+
```
260+
261+
### **C++**
262+
263+
```cpp
264+
/**
265+
* Definition for a binary tree node.
266+
* struct TreeNode {
267+
* int val;
268+
* TreeNode *left;
269+
* TreeNode *right;
270+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
271+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
272+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
273+
* };
274+
*/
275+
class BSTIterator {
276+
public:
277+
vector<int> vals;
278+
int cur;
279+
BSTIterator(TreeNode* root) {
280+
cur = 0;
281+
inorder(root);
282+
}
283+
284+
int next() {
285+
return vals[cur++];
286+
}
287+
288+
bool hasNext() {
289+
return cur < vals.size();
290+
}
291+
292+
void inorder(TreeNode* root) {
293+
if (root) {
294+
inorder(root->left);
295+
vals.push_back(root->val);
296+
inorder(root->right);
297+
}
298+
}
299+
};
300+
301+
/**
302+
* Your BSTIterator object will be instantiated and called as such:
303+
* BSTIterator* obj = new BSTIterator(root);
304+
* int param_1 = obj->next();
305+
* bool param_2 = obj->hasNext();
306+
*/
307+
```
308+
309+
```cpp
310+
/**
311+
* Definition for a binary tree node.
312+
* struct TreeNode {
313+
* int val;
314+
* TreeNode *left;
315+
* TreeNode *right;
316+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
317+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
318+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
319+
* };
320+
*/
321+
class BSTIterator {
322+
public:
323+
stack<TreeNode*> stack;
324+
BSTIterator(TreeNode* root) {
325+
for (; root != nullptr; root = root->left) {
326+
stack.push(root);
327+
}
328+
}
329+
330+
int next() {
331+
TreeNode* cur = stack.top();
332+
stack.pop();
333+
TreeNode* node = cur->right;
334+
for (; node != nullptr; node = node->left) {
335+
stack.push(node);
336+
}
337+
return cur->val;
338+
}
339+
340+
bool hasNext() {
341+
return !stack.empty();
342+
}
343+
};
344+
345+
/**
346+
* Your BSTIterator object will be instantiated and called as such:
347+
* BSTIterator* obj = new BSTIterator(root);
348+
* int param_1 = obj->next();
349+
* bool param_2 = obj->hasNext();
350+
*/
351+
```
352+
353+
### **Go**
354+
355+
```go
356+
/**
357+
* Definition for a binary tree node.
358+
* type TreeNode struct {
359+
* Val int
360+
* Left *TreeNode
361+
* Right *TreeNode
362+
* }
363+
*/
364+
type BSTIterator struct {
365+
stack []*TreeNode
366+
}
367+
368+
func Constructor(root *TreeNode) BSTIterator {
369+
var stack []*TreeNode
370+
for ; root != nil; root = root.Left {
371+
stack = append(stack, root)
372+
}
373+
return BSTIterator{
374+
stack: stack,
375+
}
376+
}
377+
378+
func (this *BSTIterator) Next() int {
379+
cur := this.stack[len(this.stack)-1]
380+
this.stack = this.stack[:len(this.stack)-1]
381+
for node := cur.Right; node != nil; node = node.Left {
382+
this.stack = append(this.stack, node)
383+
}
384+
return cur.Val
385+
}
386+
387+
func (this *BSTIterator) HasNext() bool {
388+
return len(this.stack) > 0
389+
}
390+
391+
/**
392+
* Your BSTIterator object will be instantiated and called as such:
393+
* obj := Constructor(root);
394+
* param_1 := obj.Next();
395+
* param_2 := obj.HasNext();
396+
*/
397+
```
398+
399+
## **JavaScript**
400+
401+
```js
402+
/**
403+
* Definition for a binary tree node.
404+
* function TreeNode(val, left, right) {
405+
* this.val = (val===undefined ? 0 : val)
406+
* this.left = (left===undefined ? null : left)
407+
* this.right = (right===undefined ? null : right)
408+
* }
409+
*/
410+
/**
411+
* @param {TreeNode} root
412+
*/
413+
var BSTIterator = function(root) {
414+
this.stack = []
415+
for (; root != null; root = root.left) {
416+
this.stack.push(root);
417+
}
418+
};
419+
420+
/**
421+
* @return {number}
422+
*/
423+
BSTIterator.prototype.next = function() {
424+
let cur = this.stack.pop();
425+
let node = cur.right;
426+
for (; node != null; node = node.left) {
427+
this.stack.push(node);
428+
}
429+
return cur.val;
430+
};
431+
432+
/**
433+
* @return {boolean}
434+
*/
435+
BSTIterator.prototype.hasNext = function() {
436+
return this.stack.length > 0;
437+
};
438+
439+
/**
440+
* Your BSTIterator object will be instantiated and called as such:
441+
* var obj = new BSTIterator(root)
442+
* var param_1 = obj.next()
443+
* var param_2 = obj.hasNext()
444+
*/
92445
```
93446

94447
### **...**
@@ -98,3 +451,4 @@ bSTIterator.hasNext(); // 返回 False
98451
```
99452

100453
<!-- tabs:end -->
454+

0 commit comments

Comments
 (0)