Created
August 23, 2019 17:06
-
-
Save shixiaoyu/18d5cb2b7e72bfaa12d9afc24aed333f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 BinarySearchTreeIterator { | |
private Stack<TreeNode> stack = null; | |
public BinarySearchTreeIterator(TreeNode root) { | |
this.stack = new Stack<TreeNode>(); | |
while (root != null) { | |
this.stack.push(root); | |
root = root.left; | |
} | |
} | |
/** @return whether we have a next smallest number */ | |
public boolean hasNext() { | |
return !this.stack.isEmpty(); | |
} | |
/** @return the next smallest number */ | |
// essentially using a stack to implement in-order traversal | |
public int next() { | |
// caller should check using hasNext() else NoSuchElementException | |
TreeNode t = this.stack.pop(); | |
if (t.right != null) { | |
this.stack.push(t.right); | |
TreeNode c = t.right.left; | |
while (c != null) { | |
this.stack.push(c); | |
c = c.left; | |
} | |
} | |
return t.val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment