LeetCode 0109. Convert Sorted List to Binary Search Tree Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0109. Convert Sorted List to Binary Search Tree

Description

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.

 

Example 1:

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Example 2:

Input: head = []
Output: []

 

Constraints:

  • The number of nodes in head is in the range [0, 2 * 104].
  • -105 <= Node.val <= 105

Solutions

Solution 1: DFS

We first convert the linked list to an array nums, and then use depth-first search to construct the binary search tree.

We define a function dfs(i, j), where i and j represent the current interval [i, j]. Each time, we choose the number at the middle position mid of the interval as the root node, recursively construct the left subtree for the interval [i, mid - 1], and the right subtree for the interval [mid + 1, j]. Finally, we return the node corresponding to mid as the root node of the current subtree.

In the main function, we just need to call dfs(0, n - 1) and return the result.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the linked list.

PythonJavaC++GoTypeScriptRustJavaScriptC
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]: def dfs(i: int, j: int) -> Optional[TreeNode]: if i > j: return None mid = (i + j) >> 1 l, r = dfs(i, mid - 1), dfs(mid + 1, j) return TreeNode(nums[mid], l, r) nums = [] while head: nums.append(head.val) head = head.next return dfs(0, len(nums) - 1)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !