Skip to content

Commit cf5f4f3

Browse files
authored
Update 109-convert-sorted-list-to-binary-search-tree.js
1 parent 4e956d1 commit cf5f4f3

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

109-convert-sorted-list-to-binary-search-tree.js

+21
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,24 @@ function build(arr, parent, type) {
3838
build(right, node, 'right')
3939
return node
4040
}
41+
42+
// another
43+
44+
const sortedListToBST = function(head, tail = null) {
45+
if (head === tail) {
46+
return null;
47+
} else if (head.next === tail) {
48+
return new TreeNode(head.val);
49+
} else {
50+
let slow = head;
51+
let fast = head;
52+
while (fast !== tail && fast.next !== tail) {
53+
slow = slow.next;
54+
fast = fast.next.next;
55+
}
56+
let node = new TreeNode(slow.val);
57+
node.left = sortedListToBST(head, slow);
58+
node.right = sortedListToBST(slow.next, tail);
59+
return node;
60+
}
61+
};

0 commit comments

Comments
 (0)