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;
}
相关推荐
YuTaoShao6 分钟前
【LeetCode 每日一题】3013. 将数组分成最小总代价的子数组 II
算法·leetcode·职场和发展
爱尔兰极光16 分钟前
LeetCode 热题 100--字母异位词分组
算法·leetcode·职场和发展
梵刹古音20 分钟前
【C语言】 数组基础与地址运算
c语言·开发语言·算法
im_AMBER21 分钟前
Leetcode 112 两数相加 II
笔记·学习·算法·leetcode
long31621 分钟前
KMP模式搜索算法
数据库·算法
_OP_CHEN24 分钟前
【算法基础篇】(五十三)隔板法指南:从 “分球入盒” 到不定方程,组合计数的万能解题模板
算法·蓝桥杯·c/c++·组合数学·隔板法·acm/icpc
近津薪荼28 分钟前
优选算法——滑动窗口3(子数组)
c++·学习·算法
遨游xyz28 分钟前
数据结构-栈
java·数据结构·算法
ghie909032 分钟前
基于动态规划算法的混合动力汽车能量管理建模与计算
算法·汽车·动态规划
蓝海星梦32 分钟前
GRPO 算法演进——裁剪机制篇
论文阅读·人工智能·深度学习·算法·自然语言处理·强化学习