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();
 */
相关推荐
AI科技星7 分钟前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
参.商.24 分钟前
【Day41】143. 重排链表
leetcode·golang
条tiao条1 小时前
KMP 算法详解:告别暴力匹配,让字符串匹配 “永不回头”
开发语言·算法
干啥啥不行,秃头第一名1 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
RainyJiang1 小时前
谱写Kotlin协程面试进行曲-进阶篇(第二乐章)
面试·kotlin·android jetpack
zzh940771 小时前
Gemini 3.1 Pro 硬核推理优化剖析:思维织锦、动态计算与国内实测
算法
2301_807367191 小时前
C++中的解释器模式变体
开发语言·c++·算法
愣头不青2 小时前
617.合并二叉树
java·算法
MIUMIUKK2 小时前
双指针三大例题
算法
灵感__idea2 小时前
Hello 算法:复杂问题的应对策略
前端·javascript·算法