Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
二叉树Iterator的实现,返回下一个最小的元素,
hasNext()返回是否存在下一个元素。
思路:
中序遍历压入list,定义index,返回index指向的数字,每次index++,hasNext返回index与size的比较
class BSTIterator {
List<Integer> list = new ArrayList<>();
int idx = 0;
public BSTIterator(TreeNode root) {
inOrder(root);
}
public int next() {
return list.get(idx ++);
}
public boolean hasNext() {
return idx < list.size();
}
void inOrder(TreeNode root) {
if(root == null) return;
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
}
上面的方法影响效率的地方在于向list里面不断add数字,它的size会变化,在size变化的时候list要重新规划size,移动数字,会增加计算量。
如果用链表的话会改善一些,每次add计算量都是恒定的。
class BSTIterator {
LinkedList<Integer> list = new LinkedList<>();
public BSTIterator(TreeNode root) {
inOrder(root);
}
public int next() {
return list.pollFirst();
}
public boolean hasNext() {
return list.size() > 0;
}
void inOrder(TreeNode root) {
if(root == null) return;
inOrder(root.left);
list.addLast(root.val);
inOrder(root.right);
}
}