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.
题意:写一个二叉查找树的迭代器,实现hasNext()和next()的功能。next()每次返回二叉树中未访问的最小值。要求的平均时间复杂度是O(1)和空间复杂度是O(h)。
解题思路:next()每次返回二叉树中未访问的最小值。也就是将二叉树中序遍历,并将对应值输出。这里面注意的是空间和时间的复杂度。
public class BSTIterator {//将中序遍历的功能嵌查在整个程序中 TreeNode current; Stack<TreeNode> stack; public BSTIterator(TreeNode root) { current=root; stack=new Stack<TreeNode>(); while(current!=null)//因为只可能是左节点才是最小值,将所有左子树节点入栈,保证空间复杂度是O(h) { stack.push(current); current=current.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { current=stack.pop(); int res=current.val;//这一步已经得到最小值 current=current.right;//但要考虑到右子树的遍历 while(current!=null) { stack.push(current); current=current.left; } return res; } }
时间: 2024-10-09 20:00:29