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();
 */
相关推荐
geovindu6 小时前
python:DecisionTree
开发语言·后端·python·算法
Cosolar6 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
ShineWinsu6 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu7 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
我叫黑大帅9 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
AllData公司负责人10 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康10 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长11 小时前
C++:C++11特性
开发语言·c++·算法
小酒星小杜11 小时前
年终总结,这可能是程序员最后一个冬天了
人工智能·面试·程序员