AlgoMaster Logo

Convert Sorted Array to Binary Search Tree

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Divide and Conquer

Intuition:

The problem requires us to convert a sorted array into a height-balanced binary search tree (BST). The key observation here is that for the BST to be height-balanced, the middle of the array should be selected as the root. This condition ensures that the heights of the subtrees do not vary by more than one. The left half of the array would then form the left subtree, and the right half would form the right subtree. This naturally suggests a recursive divide-and-conquer algorithm:

  1. Base Case: If the current subarray is empty, return null.
  2. Calculate the middle index of the current subarray.
  3. Create a root node using the middle element of the subarray.
  4. Recursively build the left and right subtrees using the left and right halves of the array, respectively.

Code:

2. Recursive approach using Divide and Conquer

Intuition:

While the recursive approach is intuitive, using an iterative approach can help us manage large input sizes or environments where stack depth is limited. For an iterative solution, we can use a stack to simulate the recursive calls. The stack will store not only the array indices but also pointers to the parent nodes to connect the newly created nodes as either left or right children.

  1. Use a stack to maintain a tuple of (node, left, right) where node is the parent node, and leftright are the current subarray bounds.
  2. Pop from the stack and use the middle of the current subarray to create a new TreeNode.
  3. Attach this new TreeNode to its parent node based on the side it was derived from (left or right).
  4. Push the bounds of the left and right subarrays along with references to the current TreeNode onto the stack.

Code: