-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.js
More file actions
43 lines (37 loc) · 818 Bytes
/
solution.js
File metadata and controls
43 lines (37 loc) · 818 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function(head) {
let length = 0,
p = head
while (p) {
p = p.next
length++
}
return help(head, length)
};
var help = function (head, length) {
if (length == 0) return null
let p = head,
mid = parseInt(length / 2)
for (let i = 0; i < mid; i++) p = p.next
let root = new TreeNode(p.val)
root.left = help(head, mid)
root.right = help(p.next, length - mid - 1)
return root
};