Skip to content

Commit 2912402

Browse files
committed
commit
1 parent c419daf commit 2912402

File tree

1 file changed

+21
-28
lines changed

1 file changed

+21
-28
lines changed
Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,53 @@
11
import java.util.Deque;
22
import java.util.LinkedList;
3+
import java.util.NoSuchElementException;
34

45
/**
56
* @author: wangjunchao(王俊超)
67
* @time: 2019-06-28 16:54
78
**/
89
public class BSTIterator {
910
private TreeNode root;
10-
private TreeNode curr;
11+
private TreeNode prev = null;
12+
// 最后一个元素表示next元素的值
1113
private Deque<TreeNode> deque = new LinkedList<>();
1214

1315
public BSTIterator(TreeNode root) {
1416
this.root = root;
17+
TreeNode temp = root;
18+
// 找最左的子结点,并且将经过的路径都记录下来
19+
while (temp != null) {
20+
deque.addLast(temp);
21+
temp = temp.left;
22+
}
1523
}
1624

1725
/**
1826
* @return the next smallest number
1927
*/
2028
public int next() {
2129

22-
if (curr == null) {
23-
curr = root;
24-
while (curr.left != null) {
25-
deque.addLast(curr);
26-
curr = curr.left;
27-
}
30+
if (deque.isEmpty()) {
31+
throw new NoSuchElementException();
32+
}
33+
34+
TreeNode temp = deque.removeLast();
2835

29-
return curr.val;
30-
} else {
31-
if (curr.right != null) {
32-
33-
deque.addLast(curr.right);
34-
curr = curr.right;
35-
while (curr.left != null) {
36-
deque.addLast(curr.left);
37-
curr = curr.left;
38-
}
39-
40-
41-
curr = deque.removeLast();
42-
return curr.val;
43-
} else {
44-
curr = deque.removeLast();
45-
if (curr.right != null) {
46-
deque.addLast(curr.right);
47-
}
48-
return curr.val;
36+
if (temp.right!= null) {
37+
TreeNode n = temp.right;
38+
while (n!=null) {
39+
deque.addLast(n);
40+
n = n.left;
4941
}
5042
}
5143

44+
return temp.val;
5245
}
5346

5447
/**
5548
* @return whether we have a next smallest number
5649
*/
5750
public boolean hasNext() {
58-
return curr == null || (curr.left != null || curr.right != null) || !deque.isEmpty();
51+
return !deque.isEmpty();
5952
}
6053
}

0 commit comments

Comments
 (0)