LeetCode //C - 230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k , return the k t h k^{th} kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:
  • The number of nodes in the tree is n.
  • 1 < = k < = n < = 1 0 4 1 <= k <= n <= 10^4 1<=k<=n<=104
  • 0 < = N o d e . v a l < = 1 0 4 0 <= Node.val <= 10^4 0<=Node.val<=104

From: LeetCode

Link: 230. Kth Smallest Element in a BST


Solution:

Ideas:

Here's how the algorithm will work:

  1. Perform an in-order traversal of the BST.
  2. As you traverse the nodes, keep a count of the nodes visited.
  3. When the count becomes equal to k, that node's value is the kth smallest. current node and the previous node.
Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
typedef struct {
    int count;
    int value;
} Result;

void inOrderTraversal(struct TreeNode* root, int k, Result* res) {
    if (root == NULL || res->count == k) return;

    inOrderTraversal(root->left, k, res);
    if (++res->count == k) {
        res->value = root->val;
    }
    inOrderTraversal(root->right, k, res);
}

int kthSmallest(struct TreeNode* root, int k) {
    Result res = {0, 0};
    inOrderTraversal(root, k, &res);
    return res.value;
}
相关推荐
Mxsoft61916 分钟前
AR远程定位偏差救场!某次现场故障,SLAM算法精准对齐设备模型!
算法·ar
Hello娃的27 分钟前
【量子力学】Hohenberg-Kohn 定理
人工智能·算法
老马啸西风35 分钟前
成熟企业级技术平台 MVE-010-IGA(Identity Governance & Administration,身份治理与管理)平台
人工智能·深度学习·算法·职场和发展
老马啸西风1 小时前
成熟企业级技术平台 MVE-010-app 管理平台
人工智能·深度学习·算法·职场和发展
lzh_200110121 小时前
树状数组理解
算法
R-G-B1 小时前
哈希表(hashtable),哈希理论,数组实现哈希结构 (C语言),散列理论 (拉链发、链接发),散列实现哈希结构,c++ 实现哈希
c语言·哈希算法·散列表·哈希表·数组实现哈希结构·散列实现哈希结构·c++ 实现哈希
历程里程碑1 小时前
C++ 6 :string类:高效处理字符串的秘密
c语言·开发语言·数据结构·c++·笔记·算法·排序算法
蓝色汪洋1 小时前
luogu迷宫寻路
算法
未来之窗软件服务1 小时前
幽冥大陆(四十八)P50酒店门锁SDK 苹果object c语言仙盟插件——东方仙盟筑基期
c语言·开发语言·酒店门锁·仙盟创梦ide·东方仙盟·东方仙盟sdk