108. Convert Sorted Array to Binary Search Tree
Description
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
My Solution
Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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}
*/
var sortedArrayToBST = function(nums) {
if(!nums.length){
return null;
}
let middle = Math.floor(nums.length / 2);
let node = new TreeNode(nums[middle]);
node.left = sortedArrayToBST(nums.slice(0, middle));
node.right = sortedArrayToBST(nums.slice(middle + 1, nums.length));
return node;
};
Analysis
This was a straightforward one. We take the middle element of the array and
create a new node from it. Then we look at the left half of the array and
create a new node from that and point the current node to it. Repeat for the
right half of the array. It's basic recursion. The running time is simply
O(n)
since we're just iterating over the initial array exactly
once.