Convert Sorted Array to Binary Search Tree

🏠 ⬅️ ➡️

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Example 1:

Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3] Output: [3,1] Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.

Constraints:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in a strictly increasing order.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    ! Solve the problem described in the task
    implicit none

    integer, parameter :: n = 6
    integer, dimension(n) :: nums
    type(Node), pointer :: root

    ! Example 1
    nums = [-10, -3, 0, 5, 9]
    call solve(nums, root)
    write (*, '(A)') 'Example 1:'
    call print_tree(root)

    ! Example 2
    nums = [1, 3]
    call solve(nums, root)
    write (*, '(A)') 'Example 2:'
    call print_tree(root)

contains

    subroutine solve(nums, root)
        ! Solves the problem
        implicit none
        integer, dimension(:), intent(in) :: nums
        type(Node), pointer, intent(out) :: root

        integer :: i

        allocate(root)
        root%val = nums(1)
        root%left => null()
        root%right => null()

        do i = 2, size(nums)
            call insert(root, nums(i))
        end do
    end subroutine solve

    subroutine insert(node, val)
        ! Inserts a new node into the binary search tree
        implicit none
        class(Node), pointer, intent(inout) :: node
        integer, intent(in) :: val

        if (val < node%val) then
            if (.not. associated(node%left)) then
                allocate(node%left)
                node%left%val = val
                node%left%left => null()
                node%left%right => null()
            else
                call insert(node%left, val)
            end if
        else
            if (.not. associated(node%right)) then
                allocate(node%right)
                node%right%val = val
                node%right%left => null()
                node%right%right => null()
            else
                call insert(node%right, val)
            end if
        end if
    end subroutine insert

    subroutine print_tree(node)
        ! Prints the binary search tree
        implicit none
        class(Node), pointer, intent(in) :: node

        if (associated(node)) then
            write (*, '(I0)', advance='no') node%val
            call print_tree(node%left)
            call print_tree(node%right)
        end if
    end subroutine print_tree

end program main

type Node
    integer :: val
    type(Node), pointer :: left
    type(Node), pointer :: right
end type Node
Compiled
Executed
Correct
program convert_to_height_balanced_bst
      implicit none

      integer, parameter :: max_size = 100000
      integer :: nums(max_size), i, n, current, left, right

      ! Read the input
      read (*,*) n
      do i = 1, n
        read (*,*) nums(i)
      end do

      ! Build the binary search tree
      current = 1
      left = 2
      right = 3
      while (current <= n)
        if (left <= n .and. nums(left) < nums(current)) then
          ! Left subtree is not empty
          if (right <= n .and. nums(right) < nums(left)) then
            ! Right subtree is not empty
            if (nums(right) < nums(current)) then
              ! Right subtree is smaller than current node
              write (*,*) nums(right), nums(current), nums(left)
              current = right + 1
              left = right + 1
              right = right + 2
            else
              ! Right subtree is larger than current node
              write (*,*) nums(current), nums(left), nums(right)
              current = right + 1
              left = right + 1
              right = right + 2
            end if
          else
            ! Right subtree is empty
            write (*,*) nums(current), nums(left)
            current = left + 1
            left = left + 2
          end if
        else
          ! Left subtree is empty
          if (right <= n .and. nums(right) < nums(current)) then
            ! Right subtree is not empty
            write (*,*) nums(current), nums(right)
            current = right + 1
            left = right + 1
            right = right + 2
          else
            ! Right subtree is empty
            write (*,*) nums(current)
            current = current + 1
          end if
        end if
      end do

      end program convert_to_height_balanced_bst
🌐 Data from online sources
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def sorted_array_to_bst(nums):
    def helper(start, end):
        if start > end:
            return None

        mid = start + (end - start) // 2
        node = TreeNode(nums[mid])
        node.left = helper(start, mid - 1)
        node.right = helper(mid + 1, end)

        return node

    return helper(0, len(nums) - 1)
The algorithm for creating a height-balanced binary search tree from a sorted array can be described as follows:
  1. Find the middle element of the array, and make it the root of the binary search tree.
  2. For each half of the array (elements to the left of the middle element and elements to the right of the middle element), repeat step 1 recursively.
  3. The base case is when the start index is greater than the end index, in which case a null node is returned.

The above code implements this algorithm in C++, Java, Python, and JavaScript.

🌐 Data from online sources
#include <vector>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

TreeNode* sortedArrayToBST(std::vector<int>& nums, int start, int end) {
    if (start > end) return nullptr;

    int mid = start + (end - start) / 2;
    TreeNode* node = new TreeNode(nums[mid]);
    node->left = sortedArrayToBST(nums, start, mid - 1);
    node->right = sortedArrayToBST(nums, mid + 1, end);

    return node;
}

TreeNode* sortedArrayToBST(std::vector<int>& nums) {
    return sortedArrayToBST(nums, 0, nums.size() - 1);
}
The algorithm for creating a height-balanced binary search tree from a sorted array can be described as follows:
  1. Find the middle element of the array, and make it the root of the binary search tree.
  2. For each half of the array (elements to the left of the middle element and elements to the right of the middle element), repeat step 1 recursively.
  3. The base case is when the start index is greater than the end index, in which case a null node is returned.

The above code implements this algorithm in C++, Java, Python, and JavaScript.