Convert Sorted Array to Binary Search Tree

Easy#108build a tree

You get an array of numbers sorted in increasing order. Build a binary search tree from all of them that is height-balanced: at every node, the heights of the two subtrees differ by at most one. Any such tree will do. Our array: [-7, -2, 0, 3, 8, 11] — one answer, level by level, is [0, -7, 8, none, -2, 3, 11].

input
nums: integers sorted in strictly increasing order.
returns
The root of a height-balanced binary search tree of these numbers, each once: at every node the heights of its two subtrees differ by at most one. Any such tree is right. It is written back as on LeetCode: its values level by level, null for a missing child.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums[i] < nums[i + 1]
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
function sortedArrayToBST(nums) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.