-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
47 lines (40 loc) · 1.04 KB
/
index.js
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
44
45
46
47
/**
* 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) {
if(!head) return [];
function create(head){
if(!head || head.val === null) return null;
let fast = head,slow=head;
while(fast.next && fast.next.val != null && fast.next.next && fast.next.next.val != null){
fast = fast.next.next;
slow = slow.next;
}
if(!slow.next){
let root = new TreeNode(slow.val);
return root;
}
let root = new TreeNode(slow.val);
root.right = create(slow.next)
slow.next = null;
slow.val = null;
root.left = create(head)
return root;
}
return create(head);
};