📋

Code Easy Graph

Binary Search Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def sorted_list_to_bst(nums):
    if not nums:
        return None
    
    # Find the middle index of the list
    mid = len(nums) // 2
    
    # Create a TreeNode with the middle element as the root
    root = TreeNode(nums[mid])
    
    # Recursively build the left and right subtrees
    root.left = sorted_list_to_bst(nums[:mid])
    root.right = sorted_list_to_bst(nums[mid+1:])
    
    return root