230. Kth Smallest Element in a BST Medium
1/**
2 * [230] Kth Smallest Element in a BST
3 *
4 * Given the root of a binary search tree, and an integer k, return the k^th smallest value (1-indexed) of all the values of the nodes in the tree.
5 *
6 * Example 1:
7 * <img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" style="width: 212px; height: 301px;" />
8 * Input: root = [3,1,4,null,2], k = 1
9 * Output: 1
10 *
11 * Example 2:
12 * <img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" style="width: 382px; height: 302px;" />
13 * Input: root = [5,3,6,2,4,null,null,1], k = 3
14 * Output: 3
15 *
16 *
17 * Constraints:
18 *
19 * The number of nodes in the tree is n.
20 * 1 <= k <= n <= 10^4
21 * 0 <= Node.val <= 10^4
22 *
23 *
24 * Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
25 *
26 */
27pub struct Solution {}
28use crate::util::tree::{TreeNode, to_tree};
29
30// problem: https://leetcode.com/problems/kth-smallest-element-in-a-bst/
31// discuss: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/?currentPage=1&orderBy=most_votes&query=
32
33// submission codes start here
34
35// Definition for a binary tree node.
36// #[derive(Debug, PartialEq, Eq)]
37// pub struct TreeNode {
38// pub val: i32,
39// pub left: Option<Rc<RefCell<TreeNode>>>,
40// pub right: Option<Rc<RefCell<TreeNode>>>,
41// }
42//
43// impl TreeNode {
44// #[inline]
45// pub fn new(val: i32) -> Self {
46// TreeNode {
47// val,
48// left: None,
49// right: None
50// }
51// }
52// }
53use std::rc::Rc;
54use std::cell::RefCell;
55impl Solution {
56 pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 {
57 0
58 }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_230() {
69 }
70}
71
Back
© 2025 bowen.ge All Rights Reserved.