day52(1.3)——leetcode面试经典150

173. 二叉搜索树迭代器

173. 二叉搜索树迭代器

题目:

题解:

java 复制代码
/**
 * 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 {
    private List<Integer> list = new ArrayList<>();
    private TreeNode root;
    private int l = 0;
    private void dfs(TreeNode root) {
        if(root == null) {
            return ;
        }
        list.add(root.val);
        dfs(root.left);
        dfs(root.right);
    }

    public BSTIterator(TreeNode root) {
        dfs(root);
        //对list集合进行排序
        list.sort(null);
    }
    
    public int next() {
        return list.get(l++);
    }
    
    public boolean hasNext() {
        if(l < list.size()) {
            return true;
        }
        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();
 */
相关推荐
weedsfly10 分钟前
栈和堆:JavaScript 内存的“旅馆”和“仓库”
前端·javascript·面试
SamDeepThinking23 分钟前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试
地平线开发者10 小时前
J6B vio scenario sample
算法
Ruihong18 小时前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
kyriewen19 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
BothSavage1 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn1 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽1 天前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
云技纵横1 天前
一个 @Async,把 @Transactional 的事务边界打穿了
后端·面试