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;
}
相关推荐
Fruiticecake2 分钟前
C 程序员速通现代 C++(一):lambda、std::function、移动语义与智能指针
c语言·c++
田甲19 分钟前
做一款 Type-C 母座读卡器:GL3224 双卡方案实测
c语言·开发语言
文丑颜不良啊1 小时前
LeetCode2261~2280题目解析
java·leetcode
·present·5 小时前
CSAPP(lecture 13_02 Linking)
c语言·c++
文丑颜不良啊7 小时前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode2321~2340题目解析
java·leetcode
wuyk55518 小时前
Keil工具链-第05讲-启动文件与__main到底做了什么
c语言·stm32·单片机·嵌入式硬件·物联网
文丑颜不良啊1 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z1 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
冻柠檬飞冰走茶1 天前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划