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;
}
相关推荐
_zwy16 分钟前
【C++ 多态】—— 礼器九鼎,釉下乾坤,多态中的 “风水寻龙诀“
c语言·开发语言·c++
飞川撸码2 小时前
【LeetCode 热题100】208:实现 Trie (前缀树)(详细解析)(Go语言版)
算法·leetcode·golang·图搜索算法
Fantasydg6 小时前
DAY 31 leetcode 142--链表.环形链表
算法·leetcode·链表
moz与京7 小时前
[附C++,JS,Python题解] Leetcode 面试150题(10)——轮转数组
c++·python·leetcode
拾零吖9 小时前
枚举算法-day2
数据结构·算法·leetcode
看到我,请让我去学习11 小时前
C语言快速入门-C语言基础知识
c语言·开发语言·c++·vscode
Allen Wurlitzer11 小时前
算法刷题记录——LeetCode篇(8.7) [第761~770题](持续更新)
算法·leetcode·职场和发展
Non importa12 小时前
【初阶数据结构】线性表之双链表
c语言·开发语言·数据结构·c++·考研·链表·学习方法
ydm_ymz14 小时前
初阶8 list
c语言·开发语言·数据结构·c++·list
LuckyAnJo14 小时前
Leetcode-100 回溯法-电话号码的字母组合
python·算法·leetcode