Skip to main content
Back to problems
#109
Medium Algorithms

Convert sorted list to binary search tree

Linked List Divide and Conquer Tree Binary Search Tree Binary Tree
66.1% acceptance
Feb 27, 2026
7853
173
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn sorted_list_to_bst(head: Option<Box<ListNode>>) -> Option<Rc<RefCell<TreeNode>>> {
    let mut nums = Vec::new();
    let mut curr = &head;
    while let Some(node) = curr {
      nums.push(node.val);
      curr = &node.next;
    }
    
    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)
  }
}