Swift Leetcode Series : Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree (Leetcode 109) -
Difficulty: . Link: Day 6: May Leetcode Challenge Given the head of a singly linked list where elements are sorted in…
You can check out the full story on The Swift Nerd blog with the link above.
head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Input: head = [-10,-3,0,5,9]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Input: head = 
Input: head = 
Input: head = [1,3]
- The number of nodes in
headis in the range
[0, 2 * 104].
-10^5 <= Node.val <= 10^5
In order to solve this problem, we need to understand two things completely LinkedList Basics and Tree In-order traversal (Would also add links for reference in the end). We are given a head of the linked list where the list is sorted so when we would traverse the linked list nodes till the end the order of values would be sorted. We can use this idea to have a sorted list of integers for easy access.
Now to covert a sorted list into a height balanced binary tree, We would have to recursively bisect the values with mid value being the parent node. This helps to ensure that there are roughly half nodes on both of the sides of the parent. Since we have transformed list nodes values on an array, we can easily partition the list into two halves by calculating the mid point(count/2).
We can define a helper function to recursively partition the node and we can use the binary search search like strategy on both sides to build left and right values of the tree. The for any part of the list, the root node would the middle value (mid). Then left part can be created from indexes (low…mid -1 ) and right subtree can be formed using (mid+1…end). This will recursively go on until whole list is transformed in a tree. We can simply return the tree head as result.
Optimisation : Tree In-order
Check out the detailed explanation on the blog.