Leetcode-Day14

从零开始Leetcode – Day 14

Convert Sorted List to Binary Search Tree

https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

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
48
49
/**
* 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 null;
}
var cur = head;
var count = 0;
while(cur !== null){
cur = cur.next;
count++;
}
var list = [];
list.push(head);
return helper(list, 0, count-1);
};

var helper = function(list, l, r){
if(l>r){
return null;
}
var m = Math.floor((l+r)/2);
// left
var left = helper(list, l, m-1);

var root = new TreeNode(list[0].val);
root.left = left;
list[0] = list[0].next;

// right
root.right = helper(list, m+1, r);
return root;
}