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;
}
相关推荐
祈安_2 天前
C语言内存函数
c语言·后端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874754 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐4 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
Z9fish4 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法