Created
June 30, 2018 00:46
-
-
Save Siyu-Lei/fc315f3090861bfd6d8cb4267e793d87 to your computer and use it in GitHub Desktop.
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
public class BSTIterator { | |
private Stack<TreeNode> stack; | |
private TreeNode cur; | |
public BSTIterator(TreeNode root) { | |
stack = new Stack<>(); | |
cur = root; | |
} | |
/** @return whether we have a next smallest number */ | |
public boolean hasNext() { | |
return !stack.isEmpty() || cur != null; | |
} | |
/** @return the next smallest number */ | |
public int next() { | |
while (cur != null) { // if cur == null means all left subtree node is traversed! | |
stack.push(cur); | |
cur = cur.left; | |
} | |
TreeNode node = stack.pop(); | |
cur = node.right; | |
return node.val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment