Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

BST to sorted DLL

Moderate
0/80
Average time to solve is 50m
33 upvotes
Asked in companies
AdobeFacebookGoogle

Problem statement

You are provided with a Binary Search Tree (BST), all you have to do is to convert it into the sorted doubly linked list (DLL).

For Example:

Example

Consider the above BST, it will be converted into the below sorted DLL.

Example

Here, 20 is the head node and 80 is the tail node.

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 10
0 <= N <= 10^4
-10^5 <= DATA <= 10^5

Time Limit: 1sec
Sample Input 1:
2
50 30 70 20 40 60 80 -1 -1 -1 -1 -1 -1 -1 -1
-1
Sample Output 1:
20 30 40 50 60 70 80 -1
-1
Explanation Of Sample Input 1:
For the first test case, the explanation is given in the description. -1 represents the end of DLL.

In the second test case, there is no node in BST and so, there is also no node in DLL.
Sample Input 2:
2
0 -2 -1 -3 -1 -1 -1
1 -1 2 -1 3 -1 -1
Sample Output 2:
-3 -2 0 -1
1 2 3 -1
Explanation Of Sample Input 2:
In the first test case, the sorted DLL formed is [-3, -2, 0].

In the second test case, the sorted DLL formed is [1, 2, 3].
Full screen
Console