Problem
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.
Example:
1 | BSTIterator iterator = new BSTIterator(root); |
Note:
- next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
- You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
Solution
解析
题目给定一颗bst二分查找树,要求实现一个迭代器。用bst的根节点对迭代器初始化。同时要求迭代器实现两个接口,一个next(),返回BST中下一个最小的数;hasNext()确定是否还存在下一个节点。
从例子可以看出,解决这个问题,本质上还是要确定一个有序序列,我们可以通过中序遍历得到这个有序序列,同时设定一个指针,每次调用next()接口时,我们可以直接返回当前的最小数,调用完成,对指针进行更新,指向下一个位置;hasNext()可以通过判断指针的有效性来实现。
但是,这种解法,不符合要求。题目空间复杂度要求,时间复杂度要求一致;题目要求空间复杂度为O(h),h是树的高度;这里的空间复杂度为O(n),n是树的节点数。不过,也可以通过测试。
另一种解法,不事先把中序遍历序列得到。可以先存储一部分,然后在计算得到。无论哪种方法,一定和二叉树的中序遍历有关。这里使用二叉树的非递归形式进行遍历。先把从根节点的开始,把从最左边的路径进行遍历,之后在计算,当调用next()时,先pop出栈,同时要判断当前节点的右孩子是否存在,如果存在,再对子树的左分支进行入栈。hasNext()函数通过判断栈是否为空实现。
Code
O(N)
1 | /** |
O(h)
1 | /** |