题目
https://leetcode-cn.com/problems/binary-search-tree-iterator/
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
LinkedList<Integer> list=new LinkedList<>();
public BSTIterator(TreeNode root) {
dfs(root);
}
public void dfs(TreeNode root){
if(root==null)
return;
dfs(root.left);
list.addLast(root.val);
dfs(root.right);
}
public int next() {
return list.removeFirst();
}
public boolean hasNext() {
if(!list.isEmpty()){
return true;
}
else{
return false;
}
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
复杂度
时间复杂度:初始化需要O(n) 的时间,其中 n为树中节点的数量。随后每次调用只需要 O(1) 的时间。
空间复杂度:O(n),因为需要保存中序遍历的全部结果。