Skip to main content
Back to problems
#230
Medium Algorithms

Kth smallest element in a bst

Tree Depth-First Search Binary Search Tree Binary Tree
76.5% acceptance
Feb 27, 2026
12627
261
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 {
    let mut result = 0;
    let mut count = k;
    Self::inorder(&root, &mut count, &mut result);
    result
  }
  
  fn inorder(node: &Option<Rc<RefCell<TreeNode>>>, k: &mut i32, result: &mut i32) {
    if let Some(n) = node {
      let n = n.borrow();
      Self::inorder(&n.left, k, result);
      *k -= 1;
      if *k == 0 {
        *result = n.val;
        return;
      }
      Self::inorder(&n.right, k, result);
    }
  }
}