-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_0173BinarySearchTreeIterator.java
67 lines (55 loc) · 1.59 KB
/
_0173BinarySearchTreeIterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.heatwave.leetcode.problems;
import java.util.*;
public class _0173BinarySearchTreeIterator {
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
class BSTIterator {
List<Integer> list;
Iterator<Integer> iterator;
public BSTIterator(TreeNode root) {
list = new LinkedList<>();
inorder(root, list);
iterator = list.iterator();
}
public int next() {
return iterator.next();
}
public boolean hasNext() {
return iterator.hasNext();
}
private void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}
class BSTIteratorAdvanced {
Deque<TreeNode> deque = new ArrayDeque<>();
public BSTIteratorAdvanced(TreeNode root) {
dfs(root);
}
public int next() {
TreeNode root = deque.pollLast();
int next = root.val;
root = root.right;
dfs(root);
return next;
}
public boolean hasNext() {
return !deque.isEmpty();
}
private void dfs(TreeNode root) {
while (root != null) {
deque.addLast(root);
root = root.left;
}
}
}
}