Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added BSTIterator implementation #97

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions leetcode/design/BSTIterator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class BSTIterator {
private static Queue<Integer> queue;

public BSTIterator(TreeNode root) {
queue = new LinkedList<Integer>();
inorderTraversal(root);
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !(queue.size()==0);
}

/** @return the next smallest number */
public int next() {
return queue.poll();
}

private static void inorderTraversal(TreeNode node){
if(node==null) return;
inorderTraversal(node.left);
queue.add(node.val);
inorderTraversal(node.right);
}
}

/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/