-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.js
35 lines (35 loc) · 911 Bytes
/
Solution.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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function (head) {
const nums = [];
for (; head; head = head.next) {
nums.push(head.val);
}
const dfs = (i, j) => {
if (i > j) {
return null;
}
const mid = (i + j) >> 1;
const left = dfs(i, mid - 1);
const right = dfs(mid + 1, j);
return new TreeNode(nums[mid], left, right);
};
return dfs(0, nums.length - 1);
};