forked from Wang-Jun-Chao/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c419daf
commit 2912402
Showing
1 changed file
with
21 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |