LeetCode 108: Convert Sorted Array to Binary Search Tree Solution

Master LeetCode problem 108 (Convert Sorted Array to Binary Search Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

108. Convert Sorted Array to Binary Search Tree

Problem Explanation

Explanation

To convert a sorted array into a height-balanced binary search tree, we can follow a recursive approach. The idea is to select the middle element of the array as the root of the BST. Then, recursively construct the left subtree using the left half of the array and the right subtree using the right half of the array.

Here are the steps:

  1. Define a recursive function that takes in the start and end indices of the array.
  2. Calculate the middle index (start + end) / 2.
  3. Create a new TreeNode with the value at the middle index.
  4. Recursively call the function for the left half of the array (start, mid-1) and assign the returned tree as the left child of the current node.
  5. Recursively call the function for the right half of the array (mid+1, end) and assign the returned tree as the right child of the current node.
  6. Return the current node.

The time complexity of this approach is O(n) where n is the number of elements in the array, as each element is visited once. The space complexity is also O(n) due to the recursive calls.

Solution Code

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return buildBST(nums, 0, nums.length - 1);
    }
    
    private TreeNode buildBST(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        
        root.left = buildBST(nums, start, mid - 1);
        root.right = buildBST(nums, mid + 1, end);
        
        return root;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 108 (Convert Sorted Array to Binary Search Tree)?

This page provides optimized solutions for LeetCode problem 108 (Convert Sorted Array to Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 108 (Convert Sorted Array to Binary Search Tree)?

The time complexity for LeetCode 108 (Convert Sorted Array to Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 108 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 108 in Java, C++, or Python.

Back to LeetCode Solutions