#108
Convert Sorted Array to Binary Search Tree
EasyArrayDivide and ConquerTreeBinary Search TreeBinary TreeDivide and ConquerRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach takes advantage of the sorted nature of the array. By using a divide-and-conquer strategy, we can recursively select the middle element as the root, ensuring a balanced tree.
⚙️
Algorithm
5 steps- 1Step 1: If the array is empty, return null.
- 2Step 2: Find the middle index of the array.
- 3Step 3: Create a new TreeNode with the middle element as the root.
- 4Step 4: Recursively build the left subtree using the left half of the array.
- 5Step 5: Recursively build the right subtree using the right half of the array.
solution.py15 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def sorted_array_to_bst(nums):
9 if not nums:
10 return None
11 mid = len(nums) // 2
12 root = TreeNode(nums[mid])
13 root.left = sorted_array_to_bst(nums[:mid])
14 root.right = sorted_array_to_bst(nums[mid+1:])
15 return rootℹ
Complexity note: The time complexity is O(n) because we visit each element once to construct the tree. The space complexity is O(n) due to the recursion stack in the worst case.
- 1Using the middle element of the sorted array ensures a balanced tree.
- 2Recursion can simplify the process of building the tree from the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.