109. Convert Sorted List to Binary Search Tree
My accepted JavaScript solution to LeetCode problem 109, Convert Sorted List to Binary Search Tree, running in 4ms.
- Difficulty: Medium
- JavaScript
- Runtime 4ms
- Memory 60.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 4ms, memory 60.9MB, accepted 2025-12-24.
/**
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function(head) {
if (!head) return null;
if (!head.next) return new TreeNode(head.val);
// Find middle using slow/fast pointers
let slow = head, fast = head, prev = null;
while (fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
// Disconnect left half
if (prev) prev.next = null;
// slow is the middle node
const root = new TreeNode(slow.val);
// Build subtrees
root.left = sortedListToBST(prev ? head : null);
root.right = sortedListToBST(slow.next);
return root;
};