Approach 1: Recursion
The important condition that we have to adhere to in this problem is that we have to create a
height balanced binary search tree using the set of nodes given to us in the form of a linked list. The good thing is that the nodes in the linked list are sorted in ascending order.
As we know, a binary search tree is essentially a rooted binary tree with a very special property or relationship amongst its nodes. For a given node of the binary search tree, it's value must be the value of
all the nodes in the left subtree and the value of
all the nodes in the right subtree. Since a binary tree has a recursive substructure, so does a BST i.e. all the subtrees are binary search trees in themselves.
The main idea in this approach and the next is that:
the middle element of the given list would form the root of the binary search tree. All the elements to the left of the middle element would form the left subtree recursively. Similarly, all the elements to the right of the middle element will form the right subtree of the binary search tree. This would ensure the height balance required in the resulting binary search tree.
- Since we are given a linked list and not an array, we don't really have access to the elements of the list using indexes. We want to know the middle element of the linked list.
- We can use the two pointer approach for finding out the middle element of a linked list. Essentially, we have two pointers called
slow_ptrmoves one node at a time whereas the
fast_ptrmoves two nodes at a time. By the time the
fast_ptrreaches the end of the linked list, the
slow_ptrwould have reached the middle element of the linked list. For an even sized list, any of the two middle elements can act as the root of the BST.
- Once we have the middle element of the linked list, we disconnect the portion of the list to the left of the middle element. The way we do this is by keeping a
prev_ptras well which points to one node before the
slow_ptr. For disconnecting the left portion we simply do
prev_ptr.next = None
- We only need to pass the head of the linked list to the function that converts it to a height balances BST. So, we recurse on the left half of the linked list by passing the original head of the list and on the right half by passing
slow_ptr.nextas the head.
Let's look at this algorithm in action on a sample linked list.
Time Complexity: . Suppose our linked list consists of elements. For every list we pass to our recursive function, we have to calculate the middle element for that list. For a list of size , it takes steps to find the middle element i.e. to find the mid. We do this for every half of the original linked list. From the looks of it, this seems to be an algorithm. However, on closer analysis, it turns out to be a bit more efficient than .
Let's look at the number of operations that we have to perform on each of the halves of the linked list. As we mentioned earlier, it takes steps to find the middle of a linked list with elements. After finding the middle element, we are left with two halves of size each. Then, we find the middle element for
bothof these halves and it would take a total of steps for that. And similarly for the smaller sublists that keep forming recursively. This would give us the following series of operations for a list of size .
Essentially, this is done times since we split the linked list in half every time. Hence, the above equation becomes:
Space Complexity: . Since we are resorting to recursion, there is always the added space complexity of the recursion stack that comes into picture. This could have been for a skewed tree, but the question clearly states that we need to maintain the height balanced property. This ensures the height of the tree to be bounded by . Hence, the space complexity is .
The main problem with the above solution seems to be the middle element computation. That takes up a lot of unnecessary time and this is due to the nature of the linked list data structure. Let's look at the next solution which tries to overcome this.
Approach 2: Recursion + Conversion to Array
This approach is a classic example of the time-space tradeoff.
You can get the time complexity down by using more space.
That's exactly what we're going to do in this approach. Essentially, we will convert the given linked list into an array and then use that array to form our binary search tree. In an array fetching the middle element is a operation and this will bring down the overall time complexity.
- Convert the given linked list into an array. Let's call the beginning and the end of the array as
- Find the middle element as
(left + right) / 2. Let's call this element as
mid. This is a time operation and is the only major improvement over the previous algorithm.
- The middle element forms the root of the BST.
- Recursively form binary search trees on the two halves of the array represented by
(left, mid - 1)and
(mid + 1, right)respectively.
Let's look at the implementation for this algorithm and then we will get to the complexity analysis.
- Time Complexity: The time complexity comes down to just now since we convert the linked list to an array initially and then we convert the array into a BST. Accessing the middle element now takes time and hence the time complexity comes down.
- Space Complexity: Since we used extra space to bring down the time complexity, the space complexity now goes up to as opposed to just in the previous solution. This is due to the array we construct initially.
Approach 3: Inorder Simulation
As we know, there are three different types of traversals for a binary tree:
- Preorder and
- Postorder traversals.
The inorder traversal on a binary search tree leads to a very interesting outcome.
Elements processed in the inorder fashion on a binary search tree turn out to be sorted in ascending order.
The approach listed here make use of this idea to formulate the construction of a binary search tree. The reason we are able to use this idea in this problem is because we are given a
sorted linked list initially.
Before looking at the algorithm, let us look at how the inorder traversal actually leads to a sorted order of nodes' values.
The critical idea based on the inorder traversal that we will exploit to solve this problem, is:
We know that the leftmost element in the inorder traversal has to be the head of our given linked list. Similarly, the next element in the inorder traversal will be the second element in the linked list and so on. This is made possible because the initial list given to us is sorted in ascending order.
Now that we have an idea about the relationship between the inorder traversal of a binary search tree and the numbers being sorted in ascending order, let's get to the algorithm.
Let's quickly look at a pseudo-code to make the algorithm simple to understand.
➔ function formBst(start, end) ➔ mid = (start + end) / 2 ➔ formBst(start, mid - 1) ➔ ➔ TreeNode(head.val) ➔ head = head.next ➔ ➔ formBst(mid + 1, end) ➔
- Iterate over the linked list to find out it's length. We will make use of two different pointer variables here to mark the beginning and the end of the list. Let's call them
endwith their initial values being
length - 1respectively.
- Remember, we have to simulate the inorder traversal here. We can find out the middle element by using
(start + end) / 2. Note that we don't really find out the middle node of the linked list. We just have a variable telling us the index of the middle element. We simply need this to make recursive calls on the two halves.
- Recurse on the left half by using
start, mid - 1as the starting and ending points.
- The invariance that we maintain in this algorithm is that whenever we are done building the left half of the BST, the head pointer in the linked list will point to the root node or the middle node (which becomes the root). So, we simply use the current value pointed to by
headas the root node and progress the head node by once i.e.
head = head.next
- We recurse on the right hand side using
mid + 1, endas the starting and ending points.
Let's look at an animation to make things even clearer.
- Time Complexity: The time complexity is still since we still have to process each of the nodes in the linked list once and form corresponding BST nodes.
- Space Complexity: since now the only extra space is used by the recursion stack and since we are building a height balanced BST, the height is bounded by .
Analysis written by: @sachinmalhotra1993.