LeetCode: Convert Sorted Array To Binary Search Tree Solution
Implementation
1var sortedArrayToBST = function (nums) {2 if (nums.length === 0) {3 return null4 }56 const mid = Math.floor(nums.length / 2)7 const node = new TreeNode(nums[mid])8 node.left = sortedArrayToBST(nums.slice(0, mid))9 node.right = sortedArrayToBST(nums.slice(mid + 1))1011 return node12}1314var sortedArrayToBST = function (nums) {15 const recursion = (left, right) => {16 if (left > right) {17 return null18 }1920 const mid = Math.floor((left + right) / 2)21 const node = new TreeNode(nums[mid])22 node.left = recursion(left, mid - 1)23 node.right = recursion(mid + 1, right)2425 return node26 }2728 return recursion(0, nums.length - 1)29}
References
Similar problems
Comments
Loading comments...
Tags
leetcode
tree
recursion
dfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Delete Operation For Two Strings
May 8, 2021