|
| 1 | +# 108. Convert Sorted Array to Binary Search Tree |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: Tree, Depth-first Search. |
| 5 | +- Similar Questions: Convert Sorted List to Binary Search Tree. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given an array where elements are sorted in ascending order, convert it to a height balanced BST. |
| 10 | + |
| 11 | +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. |
| 12 | + |
| 13 | +**Example:** |
| 14 | + |
| 15 | +``` |
| 16 | +Given the sorted array: [-10,-3,0,5,9], |
| 17 | +
|
| 18 | +One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: |
| 19 | +
|
| 20 | + 0 |
| 21 | + / \ |
| 22 | + -3 9 |
| 23 | + / / |
| 24 | + -10 5 |
| 25 | +``` |
| 26 | + |
| 27 | +## Solution |
| 28 | + |
| 29 | +```javascript |
| 30 | +/** |
| 31 | + * Definition for a binary tree node. |
| 32 | + * function TreeNode(val) { |
| 33 | + * this.val = val; |
| 34 | + * this.left = this.right = null; |
| 35 | + * } |
| 36 | + */ |
| 37 | +/** |
| 38 | + * @param {number[]} nums |
| 39 | + * @return {TreeNode} |
| 40 | + */ |
| 41 | +var sortedArrayToBST = function(nums) { |
| 42 | + return helper(nums, 0, nums.length - 1); |
| 43 | +}; |
| 44 | + |
| 45 | +var helper = function (nums, ll, rr) { |
| 46 | + if (ll > rr) return null; |
| 47 | + var mid = Math.ceil((ll + rr) / 2); |
| 48 | + var root = new TreeNode(nums[mid]); |
| 49 | + root.left = helper(nums, ll, mid - 1); |
| 50 | + root.right = helper(nums, mid + 1, rr); |
| 51 | + return root; |
| 52 | +}; |
| 53 | +``` |
| 54 | + |
| 55 | +**Explain:** |
| 56 | + |
| 57 | +nope. |
| 58 | + |
| 59 | +**Complexity:** |
| 60 | + |
| 61 | +* Time complexity : O(n). |
| 62 | +* Space complexity : O(n). |
0 commit comments