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();
 */
相关推荐
leoufung19 小时前
LeetCode 97. 交错字符串 - 二维DP经典题解(C语言实现)
c语言·算法·leetcode
技术小泽21 小时前
OptaPlanner入门以及实战教学
后端·面试·性能优化
leiming621 小时前
c++ map容器
开发语言·c++·算法
杨校1 天前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog1 天前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing20191 天前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人
谈笑也风生1 天前
把二叉搜索树转换为累加树(一)
算法
youngee111 天前
hot100-64跳跃游戏
算法·游戏