Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Wang-Jun-Chao committed Jun 29, 2019
1 parent c419daf commit 2912402
Showing 1 changed file with 21 additions and 28 deletions.
49 changes: 21 additions & 28 deletions [0173][Binary Search Tree Iterator]/src/BSTIterator.java
Original file line number Diff line number Diff line change
@@ -1,60 +1,53 @@
import java.util.Deque;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/**
* @author: wangjunchao(王俊超)
* @time: 2019-06-28 16:54
**/
public class BSTIterator {
private TreeNode root;
private TreeNode curr;
private TreeNode prev = null;
// 最后一个元素表示next元素的值
private Deque<TreeNode> deque = new LinkedList<>();

public BSTIterator(TreeNode root) {
this.root = root;
TreeNode temp = root;
// 找最左的子结点,并且将经过的路径都记录下来
while (temp != null) {
deque.addLast(temp);
temp = temp.left;
}
}

/**
* @return the next smallest number
*/
public int next() {

if (curr == null) {
curr = root;
while (curr.left != null) {
deque.addLast(curr);
curr = curr.left;
}
if (deque.isEmpty()) {
throw new NoSuchElementException();
}

TreeNode temp = deque.removeLast();

return curr.val;
} else {
if (curr.right != null) {

deque.addLast(curr.right);
curr = curr.right;
while (curr.left != null) {
deque.addLast(curr.left);
curr = curr.left;
}


curr = deque.removeLast();
return curr.val;
} else {
curr = deque.removeLast();
if (curr.right != null) {
deque.addLast(curr.right);
}
return curr.val;
if (temp.right!= null) {
TreeNode n = temp.right;
while (n!=null) {
deque.addLast(n);
n = n.left;
}
}

return temp.val;
}

/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return curr == null || (curr.left != null || curr.right != null) || !deque.isEmpty();
return !deque.isEmpty();
}
}

0 comments on commit 2912402

Please sign in to comment.