Algorithm-Day43-Convert-Sorted-Array-To-Binary-Search-Tree-lc-108
π§© Problem Description
Given an integer array nums where the elements are sorted in ascending order,
convert it into a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
π¬ Example
1 | Input: nums = [-10,-3,0,5,9] |
π‘ Approach: Divide and Conquer (DFS)
- The middle element of the sorted array becomes the root.
- Recursively:
- Left subarray β left subtree
- Right subarray β right subtree
- This ensures the tree is balanced because each split halves the problem.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n) β each element is processed exactly once.
- Space Complexity: O(log n) β recursion depth (balanced tree).
βοΈ Summary
- Classic divide & conquer problem.
- Key to balance is picking the middle element.
- Same pattern appears in:
lc-109(Sorted List to BST)lc-1382(Balance a BST)lc-654(Max Binary Tree β similar but different pivot choice)
Understanding this pattern is crucial for recursive tree construction problems.