【leetcode hot 100 230】二叉搜索树中第K小的元素

解法一:从小到大输出到list中,取list[k-1]就是第k小的元素

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 Solution {
    List<Integer> list = new ArrayList<>();

    public int kthSmallest(TreeNode root, int k) {
        // 从小到大输出到list中,取list[k-1]就是第k小的元素
        inoder(root);
        return list.get(k-1); 
    }

    public void inoder(TreeNode root){
        if(root==null){
            return;
        }
        inoder(root.left);
        list.add(root.val);
        inoder(root.right);
    }
}

注意:

  • list[k-1]是第k小的元素,而不是list[k]
相关推荐
xhbaitxl1 小时前
算法学习day38-动态规划
学习·算法·动态规划
多恩Stone1 小时前
【3D AICG 系列-6】OmniPart 训练流程梳理
人工智能·pytorch·算法·3d·aigc
历程里程碑1 小时前
普通数组----轮转数组
java·数据结构·c++·算法·spring·leetcode·eclipse
pp起床1 小时前
贪心算法 | part02
算法·leetcode·贪心算法
sin_hielo1 小时前
leetcode 1653
数据结构·算法·leetcode
2501_901147831 小时前
面试必看:优势洗牌
笔记·学习·算法·面试·职场和发展
YuTaoShao1 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法二)排序 + 二分查找
数据结构·算法·leetcode
wangluoqi1 小时前
26.2.6练习总结
数据结构·算法
Q741_1471 小时前
C++ 优先级队列 大小堆 模拟 力扣 703. 数据流中的第 K 大元素 每日一题
c++·算法·leetcode·优先级队列·
网安墨雨1 小时前
Python自动化一------pytes与allure结合生成测试报告
开发语言·自动化测试·软件测试·python·职场和发展·自动化