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;
    }
}
相关推荐
踩坑记录1 天前
leetcode hot100 easy 101. 对称二叉树 递归 层序遍历 bfs
算法·leetcode·宽度优先
2501_940315261 天前
leetcode182动态口令(将字符的前几个元素放在字符串后面)
算法
老鼠只爱大米1 天前
LeetCode经典算法面试题 #98:验证二叉搜索树(递归法、迭代法等五种实现方案详解)
算法·leetcode·二叉树·递归·二叉搜索树·迭代
疯狂的喵1 天前
C++编译期多态实现
开发语言·c++·算法
scx201310041 天前
20260129LCA总结
算法·深度优先·图论
2301_765703141 天前
C++中的协程编程
开发语言·c++·算法
m0_748708051 天前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习1 天前
【算法——c/c++]
c语言·c++·算法
智码未来学堂1 天前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
Halo_tjn1 天前
基于封装的专项 知识点
java·前端·python·算法