Skip to content

Commit aa70034

Browse files
committed
solve #108
1 parent d127853 commit aa70034

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,4 @@ mod n0104_maximum_depth_of_binary_tree;
108108
mod n0105_construct_binary_tree_from_preorder_and_inorder_traversal;
109109
mod n0106_construct_binary_tree_from_inorder_and_postorder_traversal;
110110
mod n0107_binary_tree_level_order_traversal_ii;
111+
mod n0108_convert_sorted_array_to_binary_search_tree;
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* [108] Convert Sorted Array to Binary Search Tree
3+
*
4+
* Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
5+
*
6+
* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
7+
*
8+
* Example:
9+
*
10+
*
11+
* Given the sorted array: [-10,-3,0,5,9],
12+
*
13+
* One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
14+
*
15+
* 0
16+
* / \
17+
* -3 9
18+
* / /
19+
* -10 5
20+
*
21+
*
22+
*/
23+
pub struct Solution {}
24+
use super::util::tree::{TreeNode, to_tree};
25+
26+
// submission codes start here
27+
28+
use std::rc::Rc;
29+
use std::cell::RefCell;
30+
impl Solution {
31+
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
32+
Solution::bst_helper(&nums[..])
33+
}
34+
35+
fn bst_helper(nums: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
36+
if nums.is_empty() { return None }
37+
Some(Rc::new(RefCell::new(TreeNode{
38+
val: nums[nums.len() / 2],
39+
left: Solution::bst_helper(&nums[0..(nums.len()/2)]),
40+
right: Solution::bst_helper(&nums[(nums.len()/2+1)..]),
41+
})))
42+
}
43+
}
44+
45+
// submission codes end
46+
47+
#[cfg(test)]
48+
mod tests {
49+
use super::*;
50+
51+
#[test]
52+
fn test_108() {
53+
assert_eq!(Solution::sorted_array_to_bst(vec![-10,-3,0,5,9]), tree![0,-3,9,-10,null,5]);
54+
assert_eq!(Solution::sorted_array_to_bst(vec![]), tree![]);
55+
}
56+
}

0 commit comments

Comments
 (0)