From 8b4dc6823dc3edb6b17860d4fef3991160518c7a Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 9 Jul 2024 09:35:27 +0800 Subject: [PATCH] 20240709 Finished --- src/problem/mod.rs | 3 +- ...vert_sorted_array_to_binary_search_tree.rs | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/problem/p108_convert_sorted_array_to_binary_search_tree.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1677e89..c2856a2 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -170,4 +170,5 @@ mod p77_combinations; mod p46_permutations; mod p39_combination_sum; mod p22_generate_parentheses; -mod p79_word_search; \ No newline at end of file +mod p79_word_search; +mod p108_convert_sorted_array_to_binary_search_tree; \ No newline at end of file diff --git a/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs b/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs new file mode 100644 index 0000000..c35ca64 --- /dev/null +++ b/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs @@ -0,0 +1,70 @@ +/** + * [108] Convert Sorted Array to Binary Search Tree + */ +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 { + pub fn sorted_array_to_bst(nums: Vec) -> Option>> { + Some(Self::array_to_bst(&nums[..])) + } + + fn array_to_bst(array: &[i32]) -> Rc> { + let length = array.len(); + + if length == 1 { + return Rc::new(RefCell::new(TreeNode::new(array[0]))); + } + + let middle = length / 2; + + let node = Rc::new(RefCell::new(TreeNode::new(array[middle]))); + + if middle != 0 { + // 左边 + let left = &array[..middle]; + node.borrow_mut().left = Some(Self::array_to_bst(left)); + } + + if middle != length - 1 { + let right = &array[middle + 1..]; + node.borrow_mut().right = Some(Self::array_to_bst(right)); + } + + return node; + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_108() { + } +}