Problem: 173. 二叉搜索树迭代器
思路
👩🏫 三叶
复杂度
时间复杂度: O ( 1 ) O(1) O(1)
空间复杂度: O ( h ) O(h) O(h)
Code
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;
}
}
}