Gjort 108
This commit is contained in:
parent
114fa8da6f
commit
c09ac53fef
2 changed files with 53 additions and 0 deletions
|
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "convert-sorted-array-to-binary-search-tree-108"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
47
convert-sorted-array-to-binary-search-tree-108/src/main.rs
Normal file
47
convert-sorted-array-to-binary-search-tree-108/src/main.rs
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
// 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct Solution {}
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
fn build_bst(nums: &[i32], start: i32, end: i32) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
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])
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue