refactor rust problems and finish p104 and p108

This commit is contained in:
2025-05-15 21:02:19 +08:00
parent 5e6299439c
commit 3b805a6422
7 changed files with 167 additions and 44 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "p108"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@@ -0,0 +1,46 @@
// 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::cell::RefCell;
use std::rc::Rc;
struct Solution;
impl Solution {
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
let length = nums.len();
if length == 0 {
return None;
}
let mid = length / 2;
let root_val = *nums.get(mid).unwrap();
let root = Rc::new(RefCell::new(TreeNode::new(root_val)));
let left = self::Solution::sorted_array_to_bst(nums[..mid].to_vec());
let right = self::Solution::sorted_array_to_bst(nums[mid + 1..].to_vec());
root.borrow_mut().left = left;
root.borrow_mut().right = right;
Some(root)
}
}
fn main() {
let test1 = [-10, -3, 0, 5, 9];
let node = Solution::sorted_array_to_bst(test1.to_vec());
println!("{:?}", node);
}