【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]
相关推荐
I_LPL2 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱3 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073213 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824964 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you5 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018725 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563245 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920746 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703316 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ6 小时前
【day60】
算法·深度优先·图论