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();
 */
相关推荐
进击的荆棘42 分钟前
递归、搜索与回溯——递归
算法·leetcode·递归
2301_822703202 小时前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_764441338 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI8 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly9 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives9 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1239 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
java1234_小锋9 小时前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
fengfuyao98510 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
xiaoye370810 小时前
Spring 中高级面试题
spring·面试