描述:
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.
思路:
这道题想了好久,知道用中序遍历来解决,用一个list将遍历的元素存储起来一下就解决了,但是空间复杂度不行。具体怎么解决,如何控制程序的终止困扰了我好久。知道我想起来至多用O(h) memory,我想到了直接把一趟遍历后返回开始之前的所有元素存储起来不就正好符合题目要求了么,bravo!
代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
List<Integer> list = new ArrayList<Integer>();// 存放结点的值
Stack<TreeNode> st = new Stack<TreeNode>();// 遍历的过程中存放结点
public BSTIterator(TreeNode root) {
if (root != null)
st.push(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
boolean flag1 = list.isEmpty(), flag2 = st.isEmpty();
if (!flag1)
return true;
if (flag1 && !flag2)
return iteratorDemo();
return false;
}
/** @return the next smallest number */
public int next() {
int num = list.get(0);
list.remove(0);
return num;
}
//中序遍历
public boolean iteratorDemo() {
TreeNode top = null;
while (!st.empty()) {
top = st.peek();
while (top.left != null) {
st.push(top.left);
top = top.left;
}
while (top.right == null) {
list.add(top.val);
st.pop();
if (!st.empty())
top = st.peek();
else
break;
}
if (!st.empty()) {
list.add(top.val);
st.pop();
st.push(top.right);
break;
}
}
if(list.isEmpty())
return false;
return true;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/