|
1 | 1 | import java.util.Deque;
|
2 | 2 | import java.util.LinkedList;
|
| 3 | +import java.util.NoSuchElementException; |
3 | 4 |
|
4 | 5 | /**
|
5 | 6 | * @author: wangjunchao(王俊超)
|
6 | 7 | * @time: 2019-06-28 16:54
|
7 | 8 | **/
|
8 | 9 | public class BSTIterator {
|
9 | 10 | private TreeNode root;
|
10 |
| - private TreeNode curr; |
| 11 | + private TreeNode prev = null; |
| 12 | + // 最后一个元素表示next元素的值 |
11 | 13 | private Deque<TreeNode> deque = new LinkedList<>();
|
12 | 14 |
|
13 | 15 | public BSTIterator(TreeNode root) {
|
14 | 16 | this.root = root;
|
| 17 | + TreeNode temp = root; |
| 18 | + // 找最左的子结点,并且将经过的路径都记录下来 |
| 19 | + while (temp != null) { |
| 20 | + deque.addLast(temp); |
| 21 | + temp = temp.left; |
| 22 | + } |
15 | 23 | }
|
16 | 24 |
|
17 | 25 | /**
|
18 | 26 | * @return the next smallest number
|
19 | 27 | */
|
20 | 28 | public int next() {
|
21 | 29 |
|
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(); |
28 | 35 |
|
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; |
49 | 41 | }
|
50 | 42 | }
|
51 | 43 |
|
| 44 | + return temp.val; |
52 | 45 | }
|
53 | 46 |
|
54 | 47 | /**
|
55 | 48 | * @return whether we have a next smallest number
|
56 | 49 | */
|
57 | 50 | public boolean hasNext() {
|
58 |
| - return curr == null || (curr.left != null || curr.right != null) || !deque.isEmpty(); |
| 51 | + return !deque.isEmpty(); |
59 | 52 | }
|
60 | 53 | }
|
0 commit comments