题目:
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.
例子:
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
题意:就是和上一题一样,在一棵二叉搜索树中,依次返回每个最小的值,此题就是典型的用递归来先序遍历得到结果,然后就是用一个判断是否存在下一个值,若存在,那么就直接再输出,否则就返回空。要求写两个函数,判断是否还存在的和取值的函数。
public class BSTIterator
{
ArrayList<Integer> list = new ArrayList<Integer>(); //全局变量非常好
int i = 0;
public BSTIterator(TreeNode root)
{
dfs(root);
}
public void dfs(TreeNode root)
{
if(root == null)
return;
else
{
if(root.left != null)
dfs(root.left);
list.add(root.val);
if(root.right != null)
dfs(root.right);
}
}
/** @return whether we have a next smallest number */
public boolean hasNext()
{
int length = list.size(); //注意,这里采用判断是否这个小于list的长度
if(i < length)
return true;
else
return false;
}
/** @return the next smallest number */
public int next()
{
int result = list.get(i).intValue(); //考虑返回
i++; //并且在这里加1
return result;
}
}
此题,和之前我博客中的那题异曲同工,可以对比着看。