# LeetCode: Convert Sorted List To Binary Search Tree Solution

1/**
2 * Definition for singly-linked list.
3 * function ListNode(val, next) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.next = (next===undefined ? null : next)
6 * }
7 */
8/**
9 * Definition for a binary tree node.
10 * function TreeNode(val, left, right) {
11 * this.val = (val===undefined ? 0 : val)
12 * this.left = (left===undefined ? null : left)
13 * this.right = (right===undefined ? null : right)
14 * }
15 */
16/**
18 * @return {TreeNode}
19 */
20var sortedListToBST = function (head) {
21 var sortedArrayToBST = function (nums) {
22 if (nums.length === 0) {
23 return null
24 }
25
26 const mid = Math.floor(nums.length / 2)
27 const node = new TreeNode(nums[mid])
28 node.left = sortedArrayToBST(nums.slice(0, mid))
29 node.right = sortedArrayToBST(nums.slice(mid + 1))
30
31 return node
32 }
33
34 const nums = []
38 }
39
40 return sortedArrayToBST(nums)
41}

leetcode

recursion

dfs

## Next Post

LeetCode: Convert Sorted Array To Binary Search Tree

May 6, 2021

Search Posts