Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4e956d1

Browse files
authoredFeb 21, 2019
Create 109-convert-sorted-list-to-binary-search-tree.js
1 parent 7563764 commit 4e956d1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
 
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val) {
11+
* this.val = val;
12+
* this.left = this.right = null;
13+
* }
14+
*/
15+
/**
16+
* @param {ListNode} head
17+
* @return {TreeNode}
18+
*/
19+
const sortedListToBST = function(head) {
20+
if(head == null) return null
21+
const arr = []
22+
let cur = head
23+
while(cur !== null) {
24+
arr.push(cur)
25+
cur = cur.next
26+
}
27+
return build(arr, null, '')
28+
};
29+
30+
function build(arr, parent, type) {
31+
if(arr.length === 0) return
32+
let mid = Math.floor(arr.length / 2)
33+
let left = arr.slice(0, mid)
34+
let right = arr.slice(mid + 1)
35+
const node = new TreeNode(arr[mid].val)
36+
if(parent) parent[type] = node
37+
build(left, node, 'left')
38+
build(right, node, 'right')
39+
return node
40+
}

0 commit comments

Comments
 (0)
Please sign in to comment.