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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
要求实现一个能返回BST最小值的树 由于要求每次取最小值只能是O(1)复杂度 所以不能每次对BST遍历求最小值。可以使用队列 在构造函数时就将BST的结果存入队列中 之后的hasNext()和next()都根据队列的状态来 代码如下:
public class BSTIterator { Queue<TreeNode> res=new LinkedList<TreeNode>(); public BSTIterator(TreeNode root) { inistack(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !res.isEmpty(); } /** @return the next smallest number */ public int next() { return res.poll().val; } public void inistack(TreeNode root){ if(root==null)return; inistack(root.left); res.offer(root); inistack(root.right); } }
Java-Binary Search Tree Iterator
原文地址:http://blog.csdn.net/u012734829/article/details/42675525