LeetCode: Convert Sorted Array To Binary Search Tree Solution

Implementation

1var sortedArrayToBST = function (nums) {
2 if (nums.length === 0) {
3 return null
4 }
5
6 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))
10
11 return node
12}
13
14var sortedArrayToBST = function (nums) {
15 const recursion = (left, right) => {
16 if (left > right) {
17 return null
18 }
19
20 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)
24
25 return node
26 }
27
28 return recursion(0, nums.length - 1)
29}

References

Original problem

Similar problems

Convert Sorted List to Binary Search Tree

Comments

Loading comments...

Tags

leetcode

tree

recursion

dfs

Next Post

LeetCode: Delete Operation For Two Strings

May 8, 2021

HoningJS

Search Posts