LeetCode: Convert Sorted List To Binary Search Tree Solution

1/**
2 * Definition for singly-linked list.
3 * function ListNode(val, next) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.next = (next===undefined ? null : next)
6 * }
7 */
8/**
9 * Definition for a binary tree node.
10 * function TreeNode(val, left, right) {
11 * this.val = (val===undefined ? 0 : val)
12 * this.left = (left===undefined ? null : left)
13 * this.right = (right===undefined ? null : right)
14 * }
15 */
16/**
17 * @param {ListNode} head
18 * @return {TreeNode}
19 */
20var sortedListToBST = function (head) {
21 var sortedArrayToBST = function (nums) {
22 if (nums.length === 0) {
23 return null
24 }
25
26 const mid = Math.floor(nums.length / 2)
27 const node = new TreeNode(nums[mid])
28 node.left = sortedArrayToBST(nums.slice(0, mid))
29 node.right = sortedArrayToBST(nums.slice(mid + 1))
30
31 return node
32 }
33
34 const nums = []
35 while (head) {
36 nums.push(head.val)
37 head = head.next
38 }
39
40 return sortedArrayToBST(nums)
41}

Comments

Loading comments...

Tags

leetcode

linked list

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: Convert Sorted Array To Binary Search Tree

May 6, 2021

Previous Post

HoningJS

Search Posts