题目描述
题目链接
https://leetcode.com/problems/binary-search-tree-iterator/
方法思路
Approach:using Queue
class BSTIterator {
//Runtime: 59 ms, faster than 91.88%
//Memory Usage: 52.7 MB, less than 9.65%
TreeNode node;
Queue<TreeNode> queue;
public BSTIterator(TreeNode root) {
node = root;
queue = new LinkedList<>();
dfs(root);
}
/** @return the next smallest number */
public int next() {
return queue.poll().val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(queue.peek() != null)
return true;
return false;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
queue.offer(root);
dfs(root.right);
}
}