Given two binary search trees, merge them into a doubly-linked list in sorted order.

For example,

Input: Below BSTs
 
      20
     /  \
   10    30
        /  \
       25  100
 
      50
     /  \
    5    70
 
 
Output: Below DDL
 
5 —> 10 —> 20 —> 25 —> 30 —> 50 —> 70 —> 100 —> null

Practice this problem

The idea is to convert each binary search tree into a doubly-linked list first in sorted order and then merge both lists into a single doubly linked list in sorted order.

 
To convert a binary search tree into a doubly-linked list in sorted order, perform reverse inorder traversal on the BST. In the reverse inorder traversal, the right child for a node is processed before its left child. We insert the node at the front of the doubly linked list for each encountered node in the reverse inorder traversal. The reverse inorder traversal is used to ensure the correct insertion order in the doubly linked list since the reverse inorder traversal visits the nodes of a BST in the decreasing order.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

5 —> 10 —> 20 —> 25 —> 30 —> 50 —> 70 —> 100 —> null

Java


Download  Run Code

Output:

5 —> 10 —> 20 —> 25 —> 30 —> 50 —> 70 —> 100 —> null

Python


Download  Run Code

Output:

5 —> 10 —> 20 —> 25 —> 30 —> 50 —> 70 —> 100 —> None

The time complexity of the above solution is O(m + n), where m is the total number of nodes in the first BST and n is the total number of nodes in the second BST. The additional space used by the program is O(x + y), where x is the height of the first tree, and y is the height of the second tree.