/108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

Easy
Arrays75.3% acceptance

Given a strictly increasing integer array arr, construct a height-balanced binary search tree (BST) from arr. Return the root node of the BST. The BST must be height-balanced, meaning the depths of the two subtrees of every node differ by no more than 1. The input array is sorted in ascending order. The output should be the root node of the BST, represented as a TreeNode object.

Example 1

Input: [2, 4, 6, 8, 10]

Output: TreeNode(6, TreeNode(4, TreeNode(2), None), TreeNode(8, None, TreeNode(10)))

Explanation: The BST rooted at 6 is height-balanced.

Example 2

Input: [7, 15]

Output: TreeNode(15, TreeNode(7), None)

Explanation: Either TreeNode(7, None, TreeNode(15)) or TreeNode(15, TreeNode(7), None) is valid.

Constraints

  • 1 <= len(arr) <= 104
  • -104 <= arr[i] <= 104
  • arr is strictly increasing
Python (current runtime)

Case 1

Input: [1, 2, 3, 4, 5, 6]

Expected: TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), None))

Case 2

Input: [11, 22, 33]

Expected: TreeNode(22, TreeNode(11), TreeNode(33))

Case 3

Input: [100]

Expected: TreeNode(100)

Case 4

Input: [-5, 0, 5, 10]

Expected: TreeNode(5, TreeNode(0, TreeNode(-5), None), TreeNode(10))