Convert Sorted Array to Binary Search Tree : Leetcode Solution.

ยท

2 min read

Convert Sorted Array to Binary Search Tree : Leetcode Solution.

Problem Statement

You are given an integer array nums where the elements are sorted in ascending order. Convert it into a height-balanced binary search tree. The problem can be found on LeetCode.


Intuition

The first thought is that a binary search tree (BST) requires the left subtree to contain elements smaller than the root, and the right subtree to contain elements greater than the root. Additionally, for the tree to be height-balanced, the depth of the two subtrees of every node should not differ by more than 1. The middle element of the array serves as a natural root since it splits the array into two equal parts, aligning with the BST properties.


Approach

  1. Find the middle element of the sorted array. This will act as the root of the BST.

  2. Recursively repeat the process for the left half of the array to construct the left subtree.

  3. Similarly, recursively repeat the process for the right half to construct the right subtree.

  4. The recursion ends when there are no elements left to process.

This approach ensures that the BST is height-balanced because we always select the middle element as the root.


Complexity

  • Time Complexity: The time complexity is $$O(n)$$ because each element is processed once to construct the tree.

  • Space Complexity: The space complexity is $$O(n)$$ due to the recursive call stack used in creating the subtrees.


Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def sortedArrayToBST(self, nums):
        if not nums:
            return None

        mid = len(nums) // 2

        root = TreeNode(nums[mid])

        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])

        return root

If you found this article helpful, you can read more of my blogs on Hashnode.

Connect with me on LinkedIn for more updates and insights.๐Ÿ˜Š

Did you find this article valuable?

Support VISHWANATH'S BLOG by becoming a sponsor. Any amount is appreciated!

ย