Convert Sorted Array to Binary Search Tree in Python

Converting a sorted array to a height-balanced binary search tree (BST) is a common algorithmic problem. A height-balanced BST is a binary tree where the depth of the two subtrees of every node never differs by more than 1.

Algorithm

The key insight is to use the middle element as the root to ensure balance. The algorithm works as follows ?

  • If the array is empty, return None
  • Find the middle element and make it the root
  • Recursively build the left subtree from elements before the middle
  • Recursively build the right subtree from elements after the middle
Sorted Array: [-10, -3, 0, 5, 9] -10 -3 0 5 9 Resulting BST: 0 -3 9 -10 5

Implementation

TreeNode Class

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

Main Solution

class Solution:
    def sortedArrayToBST(self, nums):
        if not nums:
            return None
        
        # Find middle index
        mid = len(nums) // 2
        
        # Create root with middle element
        root = TreeNode(nums[mid])
        
        # Recursively build left and right subtrees
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid + 1:])
        
        return root

# Helper function to print level order traversal
def level_order_traversal(root):
    if not root:
        return []
    
    result = []
    queue = [root]
    
    while queue:
        node = queue.pop(0)
        if node:
            result.append(node.data)
            queue.append(node.left)
            queue.append(node.right)
        else:
            result.append(None)
    
    # Remove trailing None values
    while result and result[-1] is None:
        result.pop()
    
    return result

# Example usage
nums = [-10, -3, 0, 5, 9]
solution = Solution()
bst_root = solution.sortedArrayToBST(nums)

# Print the result
result = level_order_traversal(bst_root)
print("Level order traversal:", result)
Level order traversal: [0, -3, 9, -10, None, 5, None]

How It Works

The algorithm uses the divide and conquer approach ?

  1. Base Case: If the array is empty, return None
  2. Find Middle: Calculate the middle index using integer division
  3. Create Root: Make the middle element the root of the current subtree
  4. Recursive Calls: Build left subtree from elements before middle, right subtree from elements after middle

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Each element is visited once
Space O(log n) Recursion depth for balanced tree

Alternative Approach with Indices

To avoid array slicing and improve efficiency, use indices instead ?

class Solution:
    def sortedArrayToBST(self, nums):
        def helper(left, right):
            if left > right:
                return None
            
            mid = (left + right) // 2
            root = TreeNode(nums[mid])
            
            root.left = helper(left, mid - 1)
            root.right = helper(mid + 1, right)
            
            return root
        
        return helper(0, len(nums) - 1)

# Example usage
nums = [-10, -3, 0, 5, 9]
solution = Solution()
bst_root = solution.sortedArrayToBST(nums)

result = level_order_traversal(bst_root)
print("Optimized result:", result)
Optimized result: [0, -3, 9, -10, None, 5, None]

Conclusion

Converting a sorted array to a balanced BST uses the middle element as root and recursively builds subtrees. The index-based approach is more efficient as it avoids array slicing overhead while maintaining O(n) time complexity.

Updated on: 2026-03-25T07:11:13+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements