#108
Easy Algorithms Convert sorted array to binary search tree
Array Divide and Conquer Tree Binary Search Tree Binary Tree
75.2% acceptance
Feb 27, 2026
11865
640
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Solution
Rust
Time O(n)
Space O(n)
// 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::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
fn build(nums: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
if nums.is_empty() {
return None;
}
let mid = nums.len() / 2;
let left = build(&nums[..mid]);
let right = build(&nums[mid + 1..]);
Some(Rc::new(RefCell::new(TreeNode {
val: nums[mid],
left,
right,
})))
}
build(&nums)
}
}