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函数找到最小的数字,hasnext函数判断是不是已经遍历完成,但要求时间复杂度在o(1),空间复杂度为o(h),h为树的高度。可以利用栈的特点来解决此问题,但是栈的深度我们必须保持在h,故不能把所有的节点入栈,只能入栈一部分,边出栈边入栈。
1、树的最左端的叶子节点是最小值,也是最先访问的数据,所以初始化栈时,从根节点一次把左孩子入栈,到达最左端叶子节点。
2、每次出栈,看其有孩子存在与否,存在入栈,一次到其右孩子节点的最左端的叶子节点。
3、hasnext只需判断栈是否为空即可。
代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
while(root != null){
stack.push(root);
root = root.left;
}
}
public boolean hasNext() {
return !stack.isEmpty();
}
public int next() {
TreeNode node = stack.pop();
int res = node.val;
if(node.right != null){
node = node.right;
while(node != null){
stack.push(node);
node = node.left;
}
}
return res;
}
}