Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a48f881

Browse files
committed
src/bin/convert-sorted-array-to-binary-search-tree.rs
1 parent 0e1e0af commit a48f881

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
fn main() {}
2+
3+
struct Solution;
4+
5+
// Definition for a binary tree node.
6+
#[derive(Debug, PartialEq, Eq)]
7+
pub struct TreeNode {
8+
pub val: i32,
9+
pub left: Option<Rc<RefCell<TreeNode>>>,
10+
pub right: Option<Rc<RefCell<TreeNode>>>,
11+
}
12+
13+
impl TreeNode {
14+
#[inline]
15+
pub fn new(val: i32) -> Self {
16+
TreeNode {
17+
val,
18+
left: None,
19+
right: None,
20+
}
21+
}
22+
}
23+
24+
use std::rc::Rc;
25+
use std::cell::RefCell;
26+
27+
impl Solution {
28+
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
29+
Self::build(&nums)
30+
}
31+
32+
fn build(nums: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
33+
if nums.len() == 0 {
34+
return None;
35+
}
36+
37+
let middle = nums.len() / 2;
38+
let mut root = TreeNode::new(nums[middle]);
39+
root.left = Self::build(&nums[0..middle]);
40+
root.right = Self::build(&nums[middle + 1..nums.len()]);
41+
42+
Some(Rc::new(RefCell::new(root)))
43+
}
44+
}

0 commit comments

Comments
 (0)