[LeetCode] 108. Convert Sorted Array to Binary Search Tree

The ordered array into a binary search tree. That topic is still on. As long as the output can be an effective BST. This problem may be with 109 questions do together, it requires very close but not quite the same practice. example,

Example:

Given the sorted linked list: [-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

This problem can be done recursively. Because it is the relationship between BST, and the input is an ordered array, so finding mid elements of the array, that is, to find the root of BST. code show as below

Time O (n)

Space O (n)

 1 /**
 2  * @param {number[]} nums
 3  * @return {TreeNode}
 4  */
 5 var sortedArrayToBST = function (nums) {
 6     if (!nums) return null;
 7     return helper(nums, 0, nums.length - 1);
 8 }
 9 
10 var helper = function (nums, low, high) {
11     if (low > high) return null;
12     var mid = Math.floor((high + low) / 2);
13     var node = new TreeNode(nums[mid]);
14     node.left = helper(nums, low, mid - 1);
15     node.right = helper(nums, mid + 1, high);
16     return node;
17 }

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12293678.html