-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path109.js
More file actions
38 lines (35 loc) · 913 Bytes
/
109.js
File metadata and controls
38 lines (35 loc) · 913 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
/**
* 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) {
const sortedArrayToBST = function(nums) {
if (nums.length === 0) return null;
if (nums.length === 1) return new TreeNode(nums[0]);
const midIndex = Number.parseInt(nums.length / 2);
const returnValue = new TreeNode(nums[midIndex]);
returnValue.left = sortedArrayToBST(nums.slice(0, midIndex));
returnValue.right = sortedArrayToBST(nums.slice(midIndex + 1, nums.length));
return returnValue;
};
const nums = [];
while(head) {
nums.push(head.val);
head = head.next;
}
return sortedArrayToBST(nums);
};