Topic:
Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Ideas:
Locate the intermediate data of the array as the root node, less than an array of intermediate data to construct the right subtree as the left subtree, which is larger than the array of intermediate data.
/** Definition for a binary tree node. * Function TreeNode (val) {* This.val = val; * This.left = This.right = Null * } *//** * @param {number[]} Nums * @return {TreeNode}*/varSortedarraytobst =function(nums) {varlen=nums.length; if(len==0){ return NULL; } returnBuildtree (nums,0,len-1);};functionBuildtree (nums,s,e) {if(s>e) { return NULL; } if(s==e) { return NewTreeNode (Nums[s]); } varMiddle= (s+e)/2;varRootval=Nums[middle]; varroot=NewTreeNode (Rootval); Root.left=buildtree (nums,s,middle-1); Root.right=buildtree (nums,middle+1, E); returnRoot;}
"Tree" Convert Sorted Array to Binary Search tree