From aa86d463b004eb809cccb0574180a401a0d0d331 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 18 Jun 2024 11:15:25 +0800 Subject: [PATCH] 20240618 Finished --- src/problem/mod.rs | 3 +- .../p230_kth_smallest_element_in_a_bst.rs | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 src/problem/p230_kth_smallest_element_in_a_bst.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 46aee99..6dec650 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -151,4 +151,5 @@ mod p173_binary_search_tree_iterator; mod p222_count_complete_tree_nodes; mod p199_binary_tree_right_side_view; mod p637_average_of_levels_in_binary_tree; -mod p530_minimum_absolute_difference_in_bst; \ No newline at end of file +mod p530_minimum_absolute_difference_in_bst; +mod p230_kth_smallest_element_in_a_bst; \ No newline at end of file diff --git a/src/problem/p230_kth_smallest_element_in_a_bst.rs b/src/problem/p230_kth_smallest_element_in_a_bst.rs new file mode 100644 index 0000000..fb521e8 --- /dev/null +++ b/src/problem/p230_kth_smallest_element_in_a_bst.rs @@ -0,0 +1,72 @@ +/** + * [230] Kth Smallest Element in a BST + */ +pub struct Solution {} + +use crate::util::tree::{TreeNode, to_tree}; + +// submission codes start here + +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// 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 { + fn inorder_iterate(node: &Rc>, count: &mut i32, target: i32) -> Option { + if let Some(left) = node.borrow().left.as_ref() { + if let Some(result) = Self::inorder_iterate(left, count, target) { + return Some(result); + } + }; + + *count += 1; + if *count == target { + return Some(node.borrow().val); + } + + if let Some(right) = node.borrow().right.as_ref() { + if let Some(result) = Self::inorder_iterate(right, count, target) { + return Some(result); + } + } + + None + } + + pub fn kth_smallest(root: Option>>, k: i32) -> i32 { + let mut count = 0; + + if let Some(root) = root { + return Self::inorder_iterate(&root, &mut count, k).unwrap() + } + + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_230() { + } +}