C语言 | Leetcode C语言题解之第230题二叉搜索树中第K小的元素

题目:

题解:

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int search_num(struct TreeNode* root, int k, int *result, int num)
{
    if(num == k + 1)
    {
        return k + 1; // 已找到就不往下跑了
    }

    if(root->left)
    {
        num = search_num(root->left, k, result, num);
    }
    if(num == k)
    {
        *result =  root->val;
        return k + 1; // 已找到就不往下跑了
    }
    num++;
    if(root->right)
    {
        num = search_num(root->right, k, result, num);
    }

    return num;
}

int kthSmallest(struct TreeNode* root, int k) {
    int result = 0;

    search_num(root, k, &result, 1); // 开始寻找

    return result;
}
相关推荐
Florence2320 分钟前
计算机组成原理:GPU架构、并行计算、内存层次结构等
c语言
不吃鱼的羊1 小时前
启动文件Startup_vle.c
c语言·开发语言
YuTaoShao3 小时前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵
野犬寒鸦3 小时前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
阿昭L3 小时前
leetcode两数之和
算法·leetcode
Lris-KK4 小时前
【Leetcode】高频SQL基础题--1164.指定日期的产品价格
sql·leetcode
歪歪1004 小时前
qt creator新手入门以及结合sql server数据库开发
c语言·开发语言·后端·qt·数据库开发
Swift社区7 小时前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区7 小时前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
凤年徐8 小时前
C++类和对象(上):从设计图到摩天大楼的构建艺术
c语言·开发语言·c++·类和对象