Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Note: next()
and hasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Show Tags
Have you met this question in a real interview?
Yes
No
SOLUTION 1:
使用inorder traversal把tree转化为arraylist.
递归
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
ArrayList<TreeNode> list;
int index; public BSTIterator(TreeNode root) {
list = new ArrayList<TreeNode>();
iterator(root, list); index = 0;
} // solution 1: recursion.
public void dfs (TreeNode root, ArrayList<TreeNode> ret) {
if (root == null) {
return;
} //Use inorder traversal.
dfs(root.left, ret);
ret.add(root);
dfs(root.right, ret);
} /** @return whether we have a next smallest number */
public boolean hasNext() {
if (index < list.size()) {
return true;
} return false;
} /** @return the next smallest number */
public int next() {
return list.get(index++).val;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
SOLUTION 2:
the iterator version.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ public class BSTIterator {
ArrayList<TreeNode> list;
int index; public BSTIterator(TreeNode root) {
list = new ArrayList<TreeNode>();
iterator(root, list); index = 0;
} // solution 2: Iterator.
public void iterator (TreeNode root, ArrayList<TreeNode> ret) {
if (root == null) {
return;
} Stack<TreeNode> s = new Stack<TreeNode>();
// bug 1: use push instead of put
TreeNode cur = root; while (true) {
// bug 2: should push the node into the stack.
while (cur != null) {
s.push(cur);
cur = cur.left;
} if (s.isEmpty()) {
break;
} // bug 3: should pop a node from the stack.
// deal with the top node in the satck.
cur = s.pop(); // bug 2: should be cur not root.
ret.add(cur);
cur = cur.right;
}
} /** @return whether we have a next smallest number */
public boolean hasNext() {
if (index < list.size()) {
return true;
} return false;
} /** @return the next smallest number */
public int next() {
return list.get(index++).val;
}
} /**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/