Open In App

Merge two BSTs with limited extra space

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two Binary Search Trees (BST), the task is to print the in-order traversal of merged BSTs. 

Examples:

Input: 
First BST 

Merge-two-BSTs-with-limited-extra-space-1


Second BST

Merge-two-BSTs-with-limited-extra-space-2


Output: 1 2 3 4 5 6

Input:
First BST

Merge-two-BSTs-with-limited-extra-space-3


Second BST 

Merge-two-BSTs-with-limited-extra-space-4


Output: 0 1 2 3 5 8 10 

Using Array - O(n + m) time and O(n + m) space

The idea is to perform in-order traversals of both BSTs and insert the sorted values into arrays, then merge these two sorted arrays using the standard two-pointer technique to obtain the final merged result.

Step by step approach:

  1. Traverse the both trees in in-order fashion and store their elements in two separate arrays.
  2. Use two pointers to merge the two sorted arrays by comparing elements.
  3. Add remaining elements from whichever array has leftover elements.
C++
// C++ program to Merge two BSTs with limited extra space
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to perform in-order traversal
void inorder(Node* root, vector<int>& arr) {
    if (!root) return;
    inorder(root->left, arr);
    arr.push_back(root->data);
    inorder(root->right, arr);
}

// Function to merge 2 sorted arrays.
vector<int> mergeArrays(vector<int>& arr1, vector<int>& arr2) {
    vector<int> result;
    int i = 0, j = 0;
    while (i < arr1.size() && j < arr2.size()) {
        if (arr1[i] <= arr2[j]) {
            result.push_back(arr1[i++]);
        } 
        else {
            result.push_back(arr2[j++]);
        }
    }
    while (i < arr1.size()) result.push_back(arr1[i++]);
    while (j < arr2.size()) result.push_back(arr2[j++]);
    return result;
}

vector<int> merge(Node *root1, Node *root2) {
    vector<int> arr1, arr2;
    inorder(root1, arr1);
    inorder(root2, arr2);
    return mergeArrays(arr1, arr2);
}

int main() {
    
    // Hard coded binary tree 1
    //           3
    //         /   \
    //       1      5
    Node* root1 = new Node(3);
    root1->left = new Node(1);
    root1->right = new Node(5);
    
    // Hard coded binary tree 2
    //           4
    //         /   \
    //       2      6
    Node* root2 = new Node(4);
    root2->left = new Node(2);
    root2->right = new Node(6);
    
    vector<int> res = merge(root1, root2);
    for (auto val: res) cout << val << " ";
    cout << endl;
    return 0;
}
Java
// Java program to Merge two BSTs with limited extra space
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to perform in-order traversal
    static void inorder(Node root, ArrayList<Integer> arr) {
        if (root == null) return;
        inorder(root.left, arr);
        arr.add(root.data);
        inorder(root.right, arr);
    }

    // Function to merge 2 sorted arrays.
    static ArrayList<Integer> mergeArrays(ArrayList<Integer> arr1, 
    ArrayList<Integer> arr2) {
        ArrayList<Integer> result = new ArrayList<>();
        int i = 0, j = 0;
        while (i < arr1.size() && j < arr2.size()) {
            if (arr1.get(i) <= arr2.get(j)) {
                result.add(arr1.get(i++));
            } 
            else {
                result.add(arr2.get(j++));
            }
        }
        while (i < arr1.size()) result.add(arr1.get(i++));
        while (j < arr2.size()) result.add(arr2.get(j++));
        return result;
    }

    static ArrayList<Integer> merge(Node root1, Node root2) {
        ArrayList<Integer> arr1 = new ArrayList<>();
        ArrayList<Integer> arr2 = new ArrayList<>();
        inorder(root1, arr1);
        inorder(root2, arr2);
        return mergeArrays(arr1, arr2);
    }

    public static void main(String[] args) {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        ArrayList<Integer> res = merge(root1, root2);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
# Python program to Merge two BSTs with limited extra space
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to perform in-order traversal
def inorder(root, arr):
    if not root:
        return
    inorder(root.left, arr)
    arr.append(root.data)
    inorder(root.right, arr)

# Function to merge 2 sorted arrays.
def mergeArrays(arr1, arr2):
    result = []
    i = j = 0
    while i < len(arr1) and j < len(arr2):
        if arr1[i] <= arr2[j]:
            result.append(arr1[i])
            i += 1
        else:
            result.append(arr2[j])
            j += 1
    while i < len(arr1):
        result.append(arr1[i])
        i += 1
    while j < len(arr2):
        result.append(arr2[j])
        j += 1
    return result

def merge(root1, root2):
    arr1, arr2 = [], []
    inorder(root1, arr1)
    inorder(root2, arr2)
    return mergeArrays(arr1, arr2)

if __name__ == "__main__":
    
    # Hard coded binary tree 1
    #           3
    #         /   \
    #       1      5
    root1 = Node(3)
    root1.left = Node(1)
    root1.right = Node(5)
    
    # Hard coded binary tree 2
    #           4
    #         /   \
    #       2      6
    root2 = Node(4)
    root2.left = Node(2)
    root2.right = Node(6)
    
    res = merge(root1, root2)
    for val in res:
        print(val, end=" ")
    print()
C#
// C# program to Merge two BSTs with limited extra space
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to perform in-order traversal
    static void inorder(Node root, List<int> arr) {
        if (root == null) return;
        inorder(root.left, arr);
        arr.Add(root.data);
        inorder(root.right, arr);
    }

    // Function to merge 2 sorted arrays.
    static List<int> mergeArrays(List<int> arr1, List<int> arr2) {
        List<int> result = new List<int>();
        int i = 0, j = 0;
        while (i < arr1.Count && j < arr2.Count) {
            if (arr1[i] <= arr2[j]) {
                result.Add(arr1[i++]);
            } 
            else {
                result.Add(arr2[j++]);
            }
        }
        while (i < arr1.Count) result.Add(arr1[i++]);
        while (j < arr2.Count) result.Add(arr2[j++]);
        return result;
    }

    static List<int> merge(Node root1, Node root2) {
        List<int> arr1 = new List<int>();
        List<int> arr2 = new List<int>();
        inorder(root1, arr1);
        inorder(root2, arr2);
        return mergeArrays(arr1, arr2);
    }

    static void Main() {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        List<int> res = merge(root1, root2);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Merge two BSTs with limited extra space
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to perform in-order traversal
function inorder(root, arr) {
    if (!root) return;
    inorder(root.left, arr);
    arr.push(root.data);
    inorder(root.right, arr);
}

// Function to merge 2 sorted arrays.
function mergeArrays(arr1, arr2) {
    let result = [];
    let i = 0, j = 0;
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] <= arr2[j]) {
            result.push(arr1[i++]);
        } 
        else {
            result.push(arr2[j++]);
        }
    }
    while (i < arr1.length) result.push(arr1[i++]);
    while (j < arr2.length) result.push(arr2[j++]);
    return result;
}

function merge(root1, root2) {
    let arr1 = [], arr2 = [];
    inorder(root1, arr1);
    inorder(root2, arr2);
    return mergeArrays(arr1, arr2);
}

// Hard coded binary tree 1
//           3
//         /   \
//       1      5
let root1 = new Node(3);
root1.left = new Node(1);
root1.right = new Node(5);

// Hard coded binary tree 2
//           4
//         /   \
//       2      6
let root2 = new Node(4);
root2.left = new Node(2);
root2.right = new Node(6);

let res = merge(root1, root2);
console.log(res.join(" "));

Output
1 2 3 4 5 6 

Using Stack - O(n + m) time and O(n + m) space

The idea is to simulate the in-order traversal of both trees simultaneously using two stacks, comparing the current minimum elements from both trees at each step and selecting the smaller one to add to the result.

Step by step approach:

  1. Push all left nodes of both trees onto their respective stacks until reaching leftmost nodes.
  2. Compare the top elements of both stacks to determine which has smaller value.
  3. Pop the smaller element, add it to result, and move to its right subtree.
  4. Repeat the process until both stacks are empty and no more nodes to process.
  5. Handle cases where one stack becomes empty before the other.
C++
// C++ program to Merge two BSTs with limited extra space
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

vector<int> merge(Node *root1, Node *root2) {
    vector<int> res;
    stack<Node*> s1, s2;
    
    while (root1 || root2 || !s1.empty() || !s2.empty()) {
        while (root1) {
            s1.push(root1);
            root1 = root1->left;
        }
        while (root2) {
            s2.push(root2);
            root2 = root2->left;
        }
        
        if (s2.empty() || (!s1.empty() && s1.top()->data <= s2.top()->data)) {
            root1 = s1.top();
            s1.pop();
            res.push_back(root1->data);
            root1 = root1->right;
        } 
        else {
            root2 = s2.top();
            s2.pop();
            res.push_back(root2->data);
            root2 = root2->right;
        }
    }
    return res;
}

int main() {
    
    // Hard coded binary tree 1
    //           3
    //         /   \
    //       1      5
    Node* root1 = new Node(3);
    root1->left = new Node(1);
    root1->right = new Node(5);
    
    // Hard coded binary tree 2
    //           4
    //         /   \
    //       2      6
    Node* root2 = new Node(4);
    root2->left = new Node(2);
    root2->right = new Node(6);
    
    vector<int> res = merge(root1, root2);
    for (auto val: res) cout << val << " ";
    cout << endl;
    return 0;
}
Java
// Java program to Merge two BSTs with limited extra space
import java.util.ArrayList;
import java.util.Stack;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    static ArrayList<Integer> merge(Node root1, Node root2) {
        ArrayList<Integer> res = new ArrayList<>();
        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();
        
        while (root1 != null || root2 != null || !s1.empty() || !s2.empty()) {
            while (root1 != null) {
                s1.push(root1);
                root1 = root1.left;
            }
            while (root2 != null) {
                s2.push(root2);
                root2 = root2.left;
            }
            
            if (s2.empty() || (!s1.empty() && s1.peek().data <= s2.peek().data)) {
                root1 = s1.pop();
                res.add(root1.data);
                root1 = root1.right;
            } 
            else {
                root2 = s2.pop();
                res.add(root2.data);
                root2 = root2.right;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        ArrayList<Integer> res = merge(root1, root2);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
# Python program to Merge two BSTs with limited extra space
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def merge(root1, root2):
    res = []
    s1 = []
    s2 = []
    
    while root1 or root2 or s1 or s2:
        while root1:
            s1.append(root1)
            root1 = root1.left
        while root2:
            s2.append(root2)
            root2 = root2.left
        
        if not s2 or (s1 and s1[-1].data <= s2[-1].data):
            root1 = s1.pop()
            res.append(root1.data)
            root1 = root1.right
        else:
            root2 = s2.pop()
            res.append(root2.data)
            root2 = root2.right
    return res

if __name__ == "__main__":
    
    # Hard coded binary tree 1
    #           3
    #         /   \
    #       1      5
    root1 = Node(3)
    root1.left = Node(1)
    root1.right = Node(5)
    
    # Hard coded binary tree 2
    #           4
    #         /   \
    #       2      6
    root2 = Node(4)
    root2.left = Node(2)
    root2.right = Node(6)
    
    res = merge(root1, root2)
    for val in res:
        print(val, end=" ")
    print()
C#
// C# program to Merge two BSTs with limited extra space
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    static List<int> merge(Node root1, Node root2) {
        List<int> res = new List<int>();
        Stack<Node> s1 = new Stack<Node>();
        Stack<Node> s2 = new Stack<Node>();
        
        while (root1 != null || root2 != null || 
        s1.Count > 0 || s2.Count > 0) {
            while (root1 != null) {
                s1.Push(root1);
                root1 = root1.left;
            }
            while (root2 != null) {
                s2.Push(root2);
                root2 = root2.left;
            }
            
            if (s2.Count == 0 || (s1.Count > 0 && s1.Peek().data <= s2.Peek().data)) {
                root1 = s1.Pop();
                res.Add(root1.data);
                root1 = root1.right;
            } 
            else {
                root2 = s2.Pop();
                res.Add(root2.data);
                root2 = root2.right;
            }
        }
        return res;
    }

    static void Main() {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        List<int> res = merge(root1, root2);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Merge two BSTs with limited extra space
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function merge(root1, root2) {
    let res = [];
    let s1 = [];
    let s2 = [];
    
    while (root1 || root2 || s1.length > 0 || s2.length > 0) {
        while (root1) {
            s1.push(root1);
            root1 = root1.left;
        }
        while (root2) {
            s2.push(root2);
            root2 = root2.left;
        }
        
        if (s2.length === 0 || (s1.length > 0 && s1[s1.length-1].data <= s2[s2.length-1].data)) {
            root1 = s1.pop();
            res.push(root1.data);
            root1 = root1.right;
        } 
        else {
            root2 = s2.pop();
            res.push(root2.data);
            root2 = root2.right;
        }
    }
    return res;
}

// Hard coded binary tree 1
//           3
//         /   \
//       1      5
let root1 = new Node(3);
root1.left = new Node(1);
root1.right = new Node(5);

// Hard coded binary tree 2
//           4
//         /   \
//       2      6
let root2 = new Node(4);
root2.left = new Node(2);
root2.right = new Node(6);

let res = merge(root1, root2);
console.log(res.join(" "));

Output
1 2 3 4 5 6 

Using Doubly Linked List - O(n + m) time and O(n + m) space

Follow the steps below to solve the problem:

C++
// C++ program to Merge two BSTs with limited extra space
#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to convert bst into ll 
void convertToLL(Node* root, Node*& head, Node*& tail) {
    if (!root) return;
    
    convertToLL(root->left, head, tail);
    
    if (!head) {
        head = tail = root;
    } 
    else {
        tail->right = root;
        root->left = tail;
        tail = root;
    }
    
    convertToLL(root->right, head, tail);
}

vector<int> merge(Node *root1, Node *root2) {
    Node* head1 = nullptr, *tail1 = nullptr;
    Node* head2 = nullptr, *tail2 = nullptr;
    
    convertToLL(root1, head1, tail1);
    convertToLL(root2, head2, tail2);
    
    vector<int> result;
    Node* curr1 = head1, *curr2 = head2;
    
    // Merge the sorted lists 
    while (curr1 && curr2) {
        if (curr1->data <= curr2->data) {
            result.push_back(curr1->data);
            curr1 = curr1->right;
        } 
        else {
            result.push_back(curr2->data);
            curr2 = curr2->right;
        }
    }
    
    while (curr1) {
        result.push_back(curr1->data);
        curr1 = curr1->right;
    }
    
    while (curr2) {
        result.push_back(curr2->data);
        curr2 = curr2->right;
    }
    
    return result;
}

int main() {
    
    // Hard coded binary tree 1
    //           3
    //         /   \
    //       1      5
    Node* root1 = new Node(3);
    root1->left = new Node(1);
    root1->right = new Node(5);
    
    // Hard coded binary tree 2
    //           4
    //         /   \
    //       2      6
    Node* root2 = new Node(4);
    root2->left = new Node(2);
    root2->right = new Node(6);
    
    vector<int> res = merge(root1, root2);
    for (auto val: res) cout << val << " ";
    cout << endl;
    return 0;
}
Java
// Java program to Merge two BSTs with limited extra space
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to convert bst into ll 
    static void convertToLL(Node root, Node[] head, Node[] tail) {
        if (root == null) return;
        
        convertToLL(root.left, head, tail);
        
        if (head[0] == null) {
            head[0] = tail[0] = root;
        } 
        else {
            tail[0].right = root;
            root.left = tail[0];
            tail[0] = root;
        }
        
        convertToLL(root.right, head, tail);
    }

    static ArrayList<Integer> merge(Node root1, Node root2) {
        Node[] head1 = new Node[1], tail1 = new Node[1];
        Node[] head2 = new Node[1], tail2 = new Node[1];
        
        convertToLL(root1, head1, tail1);
        convertToLL(root2, head2, tail2);
        
        ArrayList<Integer> result = new ArrayList<>();
        Node curr1 = head1[0], curr2 = head2[0];
        
        // Merge the sorted lists 
        while (curr1 != null && curr2 != null) {
            if (curr1.data <= curr2.data) {
                result.add(curr1.data);
                curr1 = curr1.right;
            } 
            else {
                result.add(curr2.data);
                curr2 = curr2.right;
            }
        }
        
        while (curr1 != null) {
            result.add(curr1.data);
            curr1 = curr1.right;
        }
        
        while (curr2 != null) {
            result.add(curr2.data);
            curr2 = curr2.right;
        }
        
        return result;
    }

    public static void main(String[] args) {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        ArrayList<Integer> res = merge(root1, root2);
        for (int val : res) System.out.print(val + " ");
        System.out.println();
    }
}
Python
# Python program to Merge two BSTs with limited extra space
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to convert bst into ll 
def convertToLL(root, head, tail):
    if root is None:
        return
    
    convertToLL(root.left, head, tail)
    
    if head[0] is None:
        head[0] = tail[0] = root
    else:
        tail[0].right = root
        root.left = tail[0]
        tail[0] = root
    
    convertToLL(root.right, head, tail)

def merge(root1, root2):
    head1, tail1 = [None], [None]
    head2, tail2 = [None], [None]
    
    convertToLL(root1, head1, tail1)
    convertToLL(root2, head2, tail2)
    
    result = []
    curr1, curr2 = head1[0], head2[0]
    
    # Merge the sorted lists 
    while curr1 and curr2:
        if curr1.data <= curr2.data:
            result.append(curr1.data)
            curr1 = curr1.right
        else:
            result.append(curr2.data)
            curr2 = curr2.right
    
    while curr1:
        result.append(curr1.data)
        curr1 = curr1.right
    
    while curr2:
        result.append(curr2.data)
        curr2 = curr2.right
    
    return result

if __name__ == "__main__":
    
    # Hard coded binary tree 1
    #           3
    #         /   \
    #       1      5
    root1 = Node(3)
    root1.left = Node(1)
    root1.right = Node(5)
    
    # Hard coded binary tree 2
    #           4
    #         /   \
    #       2      6
    root2 = Node(4)
    root2.left = Node(2)
    root2.right = Node(6)
    
    res = merge(root1, root2)
    for val in res:
        print(val, end=" ")
    print()
C#
// C# program to Merge two BSTs with limited extra space
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function to convert bst into ll 
    static void convertToLL(Node root, ref Node head, ref Node tail) {
        if (root == null) return;
        
        convertToLL(root.left, ref head, ref tail);
        
        if (head == null) {
            head = tail = root;
        } 
        else {
            tail.right = root;
            root.left = tail;
            tail = root;
        }
        
        convertToLL(root.right, ref head, ref tail);
    }

    static List<int> merge(Node root1, Node root2) {
        Node head1 = null, tail1 = null;
        Node head2 = null, tail2 = null;
        
        convertToLL(root1, ref head1, ref tail1);
        convertToLL(root2, ref head2, ref tail2);
        
        List<int> result = new List<int>();
        Node curr1 = head1, curr2 = head2;
        
        // Merge the sorted lists 
        while (curr1 != null && curr2 != null) {
            if (curr1.data <= curr2.data) {
                result.Add(curr1.data);
                curr1 = curr1.right;
            } 
            else {
                result.Add(curr2.data);
                curr2 = curr2.right;
            }
        }
        
        while (curr1 != null) {
            result.Add(curr1.data);
            curr1 = curr1.right;
        }
        
        while (curr2 != null) {
            result.Add(curr2.data);
            curr2 = curr2.right;
        }
        
        return result;
    }

    static void Main() {
        
        // Hard coded binary tree 1
        //           3
        //         /   \
        //       1      5
        Node root1 = new Node(3);
        root1.left = new Node(1);
        root1.right = new Node(5);
        
        // Hard coded binary tree 2
        //           4
        //         /   \
        //       2      6
        Node root2 = new Node(4);
        root2.left = new Node(2);
        root2.right = new Node(6);
        
        List<int> res = merge(root1, root2);
        foreach (int val in res) Console.Write(val + " ");
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Merge two BSTs with limited extra space
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to convert bst into ll 
function convertToLL(root, head, tail) {
    if (root === null) return;
    
    convertToLL(root.left, head, tail);
    
    if (head[0] === null) {
        head[0] = tail[0] = root;
    } 
    else {
        tail[0].right = root;
        root.left = tail[0];
        tail[0] = root;
    }
    
    convertToLL(root.right, head, tail);
}

function merge(root1, root2) {
    let head1 = [null], tail1 = [null];
    let head2 = [null], tail2 = [null];
    
    convertToLL(root1, head1, tail1);
    convertToLL(root2, head2, tail2);
    
    let result = [];
    let curr1 = head1[0], curr2 = head2[0];
    
    // Merge the sorted lists 
    while (curr1 && curr2) {
        if (curr1.data <= curr2.data) {
            result.push(curr1.data);
            curr1 = curr1.right;
        } 
        else {
            result.push(curr2.data);
            curr2 = curr2.right;
        }
    }
    
    while (curr1) {
        result.push(curr1.data);
        curr1 = curr1.right;
    }
    
    while (curr2) {
        result.push(curr2.data);
        curr2 = curr2.right;
    }
    
    return result;
}

// Hard coded binary tree 1
//           3
//         /   \
//       1      5
let root1 = new Node(3);
root1.left = new Node(1);
root1.right = new Node(5);

// Hard coded binary tree 2
//           4
//         /   \
//       2      6
let root2 = new Node(4);
root2.left = new Node(2);
root2.right = new Node(6);

let res = merge(root1, root2);
console.log(res.join(" "));

Output
1 2 3 4 5 6 

Similar Reads