diff --git a/convert-sorted-array-to-binary-search-tree-108/Cargo.toml b/convert-sorted-array-to-binary-search-tree-108/Cargo.toml new file mode 100644 index 0000000..1f00adf --- /dev/null +++ b/convert-sorted-array-to-binary-search-tree-108/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "convert-sorted-array-to-binary-search-tree-108" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/convert-sorted-array-to-binary-search-tree-108/src/main.rs b/convert-sorted-array-to-binary-search-tree-108/src/main.rs new file mode 100644 index 0000000..8fe7e62 --- /dev/null +++ b/convert-sorted-array-to-binary-search-tree-108/src/main.rs @@ -0,0 +1,47 @@ +// 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, + } + } +} +struct Solution {} + +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn sorted_array_to_bst(nums: Vec) -> Option>> { + fn build_bst(nums: &[i32], start: i32, end: i32) -> Option>> { + if start > end { + return None; + } + + let mid = (start + end) / 2; + Some(Rc::new(RefCell::new(TreeNode { + val: nums[mid as usize], + left: build_bst(nums, start, mid - 1), + right: build_bst(nums, mid + 1, end), + }))) + } + + build_bst(&nums, 0, (nums.len() as i32) - 1) + } +} + +fn main() { + println!( + "{:?}", + Solution::sorted_array_to_bst(vec![-10, -3, 0, 5, 9]) + ); +}