Sorted Doubly Linked List to Balanced BST

Easy
0/40
0 upvote
Asked in company
Josh Technology Group

Problem statement

You are given a special linked list that is sorted in ascending order. Each node in this list is a doubly linked list node, containing data, a next pointer to the next node, and a prev pointer to the previous node.


Your task is to convert this sorted doubly linked list into a height-balanced Binary Search Tree (BST).


A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. The BST property must also be maintained: for any given node, all values in its left subtree are less than the node's value, and all values in its right subtree are greater.


Your function should take the head of the doubly linked list and return the root of the newly constructed BST.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of input contains the node data for the sorted doubly linked list, separated by single spaces. The input is terminated by -1.


Output Format:
Print the level-order traversal of the constructed BST. Each level of the tree should be on a new line, with node values on the same level separated by spaces. A null child should not be printed.
Sample Input 1:
1 2 3 4 5 6 7 -1


Sample Output 1:
4 
2 6 
1 3 5 7


Explanation for Sample 1:
The middle of [1,2,3,4,5,6,7] is 4. 4 becomes the root.
The left half [1,2,3] is used to build the left subtree. Its middle is 2.
The right half [5,6,7] is used to build the right subtree. Its middle is 6.
This process continues recursively, resulting in a balanced BST.


Sample Input 2:
10 20 30 40 50 60 -1


Sample Output 2:
30 
20 50 
10 40 60


Explanation for Sample 2:
The list has an even number of elements. The first of the two middle elements, 30, is chosen as the root.
Left half: [10, 20]. Middle is 10. 20 becomes its right child.
Right half: [40, 50, 60]. Middle is 50. 40 is its left child, 60 is its right.
The resulting tree is height-balanced.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
0 <= Number of nodes <= 1000
-1000 <= Node Value <= 1000
The input list is guaranteed to be sorted.

Time limit: 1 sec
Approaches (1)
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Sorted Doubly Linked List to Balanced BST
Full screen
Console