Skip to content

Commit e70803c

Browse files
committed
'Convert Sorted Array to Binary Search Tree' soln
1 parent 1527cce commit e70803c

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
///
2+
/// Problem: Convert Sorted Array to Binary Search Tree
3+
///
4+
/// Given an integer array nums where the elements are sorted in ascending order,
5+
/// convert it to a height-balanced binary search tree.
6+
///
7+
/// A height-balanced binary tree is a binary tree in which the depth of the two
8+
/// subtrees of every node never differs by more than one.
9+
///
10+
/// Example 1:
11+
/// Input: nums = [-10,-3,0,5,9]
12+
/// Output: [0,-3,9,-10,null,5]
13+
/// Explanation: [0,-10,5,null,-3,null,9] is also accepted.
14+
///
15+
/// Example 2:
16+
/// Input: nums = [1,3]
17+
/// Output: [3,1]
18+
///
19+
/// Constraints:
20+
/// 1 <= nums.length <= 10^4
21+
/// -10^4 <= nums[i] <= 10^4
22+
/// nums is sorted in a strictly increasing order.
23+
///
24+
25+
// Definition for a binary tree node (provided by LeetCode)
26+
// #[derive(Debug, PartialEq, Eq)]
27+
// pub struct TreeNode {
28+
// pub val: i32,
29+
// pub left: Option<Rc<RefCell<TreeNode>>>,
30+
// pub right: Option<Rc<RefCell<TreeNode>>>,
31+
// }
32+
//
33+
// impl TreeNode {
34+
// #[inline]
35+
// pub fn new(val: i32) -> Self {
36+
// TreeNode {
37+
// val,
38+
// left: None,
39+
// right: None
40+
// }
41+
// }
42+
// }
43+
44+
// # Solution
45+
// Time complexity: O(n)
46+
// Space complexity: O(log n)
47+
48+
49+
use std::rc::Rc;
50+
use std::cell::RefCell;
51+
impl Solution {
52+
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
53+
Self::helper(&nums, 0, nums.len() as i32 - 1)
54+
}
55+
56+
fn helper(nums: &[i32], left: i32, right: i32) -> Option<Rc<RefCell<TreeNode>>> {
57+
if left > right {
58+
return None;
59+
}
60+
61+
62+
let mid = left + (right - left) / 2;
63+
64+
65+
let mut root = TreeNode::new(nums[mid as usize]);
66+
67+
68+
root.left = Self::helper(nums, left, mid - 1);
69+
root.right = Self::helper(nums, mid + 1, right);
70+
71+
Some(Rc::new(RefCell::new(root)))
72+
}
73+
}

0 commit comments

Comments
 (0)