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;
}
相关推荐
Xin77011 小时前
LeetCode 23.合并 K 个升序链表(分治递归)
leetcode
qq_5896660514 小时前
C语言、C++与C#的区别详解
c语言·c++·c#
Nil20814 小时前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
Nil20815 小时前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
cz071015 小时前
hot100_搜索二维矩阵 II
算法·leetcode
昌原的儿子LEO17 小时前
Linux进程知识点总结
linux·服务器·c语言·数据库
圣保罗的大教堂17 小时前
leetcode 3718. 缺失的最小倍数 简单
leetcode
青 春 记 忆18 小时前
LeetCode 234. 回文链表|Python 解法详解
python·leetcode·链表
啊嘞嘞?19 小时前
力扣(LRU缓存)
算法·leetcode
啊嘞嘞?20 小时前
力扣(下一个排列)
算法·leetcode