day58(1.9)——leetcode面试经典150

230. 二叉搜索树中第 K 小的元素

230. 二叉搜索树中第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 {
    private int x = -1;
    private int t = 0;
    public void dfs(TreeNode root, int k) {
        if(root == null || x != -1) {
            return;
        }
        dfs(root.left, k);
        t++;
        if(t==k) {
            x = root.val;
        }
        dfs(root.right, k);
    }


    public int kthSmallest(TreeNode root, int k) {
        dfs(root, k);
        return x;
    }
}
相关推荐
LK_072 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi2 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK2 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
宋艳_AI应用开发2 小时前
Agent 工程:慢的不一定是模型,答案对了也可能算失败
面试
文丑颜不良啊3 小时前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司4 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
斯维赤5 小时前
三级缓存为什么是三级?二级缓存不够吗
前端·后端·面试
Rain的Java大神之路5 小时前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
阿庆_AI研发工程师5 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户7341681035486 小时前
基于MindSpore的深度残差收缩网络程序
算法