


If the given linked list is [1,4,5,8,9], then the balanced BST will :

We will be using a single structure, ‘NODE’, to define both the List Node and Tree Node.
It will have the following members:
1. 'VAL' to store the integer data value.
2. 'PREV' pointer to store the address of the previous node and also used to store the address of the left child.
3. 'NEXT' pointer to store the address of the next node and also used to store the address of the right child.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains the ‘N’ denoting the number of elements in the linked list.
The second line contains ‘N’ integers denoting the given linked list.
For each test case, print the inorder traversal of the constructed balanced BST.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6
1 <= nodeVal <=10^9
Time limit: 1 sec
In this approach, we will first find the number of elements present in the list using a ‘COUNTNODE(‘HEAD’)’ function. We will also define a REC(‘CURNODE’, ‘N’) that will return the root of the constructed BST of the first ‘N’ elements. We will first place the leftmost node, then the middle, then the right subtree similar to inorder manner. We will make the left subtree with ‘N’/2 nodes and the right subtree with the remaining nodes. While constructing the BST, we will store the ‘HEAD’ pointer in a global variable ‘CURNODE’ so that we keep moving the list head pointer to the next so that we have the appropriate pointer in each recursive call.
Algorithm:
In this approach, we will create a recursive function REC(‘CURNODE’) that will first find the middle of the linked list starting from ‘CURNODE’ using Floyd’s Algorithm (Hare and Tortoise Algorithm) and make a new node ‘ROOT’ having the ‘VAL’ as ‘VAL’ of the middle element. We are splitting the list in the middle because we have to follow the property of balanced BST. Now, we will make two recursive calls for the left and right subtree. In the end, we will return the ‘ROOT’ node.
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators
Gray Code Transformation
Count of Subsequences with Given Sum