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;
}
相关推荐
在风中的意志20 小时前
[数据库SQL] [leetcode-175] 175. 组合两个表
数据库·sql·leetcode
圣保罗的大教堂20 小时前
leetcode 1970. 你能穿过矩阵的最后一天 困难
leetcode
造夢先森20 小时前
常见数据结构及算法
数据结构·算法·leetcode·贪心算法·动态规划
越努力^越幸运20 小时前
C中内存函数
c语言·开发语言
iAkuya20 小时前
(leetcode)力扣100 29删除链表的倒数第 N 个结点(双指针)
算法·leetcode·链表
良木生香20 小时前
【数据结构-初阶】二叉树---链式存储
c语言·数据结构·c++·算法·蓝桥杯·深度优先
Binky67821 小时前
力扣--贪心(2)+动规(1)
算法·leetcode·职场和发展
长安er1 天前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓1 天前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
小白菜又菜1 天前
Leetcode 1925. Count Square Sum Triples
算法·leetcode