Convert Sorted List to Binary Search Tree LeetCode solution in JavaScript

1
var sortedListToBST = function (head) {
2
if (!head) return null;
3
if (!head.next) return new TreeNode(head.val);
4

5
let fast = head,
6
slow = head,
7
prev = head;
8
while (fast && fast.next) {
9
prev = slow;
10
slow = slow.next;
11
fast = fast.next.next;
12
}
13

14
const root = new TreeNode(slow.val);
15
prev.next = null;
16

17
const newHead = slow.next;
18
slow.next = null;
19

20
root.left = sortedListToBST(head);
21
root.right = sortedListToBST(newHead);
22

23
return root;
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0