Description
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.
问题描述
实现二叉搜索树迭代器。迭代器初始化为树的根节点
调用next()返回BST中的下一个最小的树
注意:next()和hasNext()需要是O(1)的时间复杂度,O(h)的空间复杂度,h为树的高度。
问题分析
使用stack保存二叉搜索树节点。
- 构造函数中将从根节点到最左节点之间的节点入栈。
- hasNext()判断栈是否空
- next(),获取出栈节点,判断是否有右子树,若有,则将右子树根节点到其最左节点之间的节点入栈。返回出栈节点的值。
解法
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack();
TreeNode cur = root;
while(cur != null){
stack.push(cur);
if(cur.left != null) cur = cur.left;
else break;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
TreeNode cur = node;
// traversal right branch
if(cur.right != null){
cur = cur.right;
while(cur != null){
stack.push(cur);
if(cur.left != null) cur = cur.left;
else break;
}
}
return node.val;
}
}