Problem: 173. 二叉搜索树迭代器
思路
复杂度
时间复杂度: O ( 1 ) O(1) O(1)
空间复杂度: O ( h ) O(h) O(h)
Code
Java
class BSTIterator {
Stack<TreeNode> d = new Stack<>();
public BSTIterator(TreeNode root)
{
dfsLeft(root);
}
public int next()
{
TreeNode root = d.pop();
int ans = root.val;
root = root.right;
dfsLeft(root);
return ans;
}
public boolean hasNext()
{
return !d.isEmpty();
}
void dfsLeft(TreeNode root)
{
while (root != null)
{
d.push(root);
root = root.left;
}
}
}