LeetCode 173 - Binary Search Tree Iterator

作者 QIFAN 日期 2017-01-29
LeetCode 173 - Binary Search Tree Iterator

原题链接: 173. Binary Search Tree Iterator


题干

实现 BST 的 Iterator ,要求 average $O(1)$ 时间与 $O(h)$ 空间。

思路

中序遍历,使用一个 stack 保存父节点。

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
TreeNode curr;
Stack<TreeNode> parents;
public BSTIterator(TreeNode root) {
curr = root;
parents = new Stack<>();
while (curr != null) {
parents.push(curr);
curr = curr.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return curr != null || !parents.isEmpty();
}
/** @return the next smallest number */
public int next() {
if (curr == null) {
curr = parents.pop();
}
int res = curr.val;
if (curr != null) {
curr = curr.right;
while (curr != null) {
parents.push(curr);
curr = curr.left;
}
} else {
if (parents.isEmpty()) {
curr = null;
} else {
curr = parents.pop();
}
}
return res;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/