-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathConvert Sorted List to Binary Search Tree.js
99 lines (80 loc) · 1.75 KB
/
Convert Sorted List to Binary Search Tree.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
*/
/**
* 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) {
var len = 0,
node = head;
if (!node) {
return null;
}
while (node) {
len++;
node = node.next;
}
curNode = head;
return helper(0, len - 1);
},
curNode;
// build tree bottom up
function helper(start, end) {
if (start > end) {
return null;
}
var mid = parseInt((start + end) / 2),
left,
right,
node;
left = helper(start, mid - 1),
node = new TreeNode(curNode.val);
curNode = curNode.next;
right = helper(mid + 1, end);
node.left = left;
node.right = right;
return node;
}
// solution 2
var sortedListToBST = function(head) {
var arr = [],
node = head,
len;
if (!node) {
return null;
}
while (node) {
arr.push(node);
node = node.next;
}
len = arr.length;
if (len === 1) {
return head;
}
return getMidNode(0, len - 1, arr);
};
function getMidNode(start, end, arr) {
if (start > end) {
return null;
}
var mid = parseInt((start + end) / 2),
node = new TreeNode(arr[mid].val);
node.left = getMidNode(start, mid - 1, arr);
node.right = getMidNode(mid + 1, end, arr);
return node;
}