Similar Problems

Similar Problems not available

Merge Bsts To Create Single Bst - Leetcode Solution

Companies:

LeetCode:  Merge Bsts To Create Single Bst Leetcode Solution

Difficulty: Hard

Topics: hash-table binary-search depth-first-search tree binary-tree  

Problem Statement:

Given two Binary Search Trees (BST) merge them into a single BST.

Solution:

We can solve this problem recursively. The idea is to merge the nodes of the two trees into a single tree with the help of a third tree.

  1. Create an empty binary search tree to hold the merged values.
  2. Traverse the first BST and add all nodes to the third tree (the empty one).
  3. Traverse the second BST and add all nodes to the third tree.
  4. Return the root node of the third tree.

Let's write a function that will merge two BSTs:

TreeNode* merge(TreeNode* root1, TreeNode* root2) {
    if (root1 == nullptr && root2 == nullptr) {
        return nullptr;
    }

    TreeNode* root3 = new TreeNode();

    if (root1 == nullptr) {
        root3->val = root2->val;
        root3->left = merge(root1, root2->left);
        root3->right = merge(root1, root2->right);
        return root3;
    }

    if (root2 == nullptr) {
        root3->val = root1->val;
        root3->left = merge(root1->left, root2);
        root3->right = merge(root1->right, root2);
        return root3;
    }

    root3->val = root1->val + root2->val;
    root3->left = merge(root1->left, root2->left);
    root3->right = merge(root1->right, root2->right);

    return root3;
}

Now, let's write a wrapper function that will call merge and return the root of the merged tree:

TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
    return merge(root1, root2);
}

We can test the solution by creating two binary search trees and merging them:

    5            3
   / \          / \
  3   8        2   7
    
merged tree:
    8
   / \
  5   15
 / \   \
3   7   8

Code:

class Solution {
public:
    TreeNode* merge(TreeNode* root1, TreeNode* root2) {
        if (root1 == nullptr && root2 == nullptr) {
            return nullptr;
        }

        TreeNode* root3 = new TreeNode();

        if (root1 == nullptr) {
            root3->val = root2->val;
            root3->left = merge(root1, root2->left);
            root3->right = merge(root1, root2->right);
            return root3;
        }

        if (root2 == nullptr) {
            root3->val = root1->val;
            root3->left = merge(root1->left, root2);
            root3->right = merge(root1->right, root2);
            return root3;
        }

        root3->val = root1->val + root2->val;
        root3->left = merge(root1->left, root2->left);
        root3->right = merge(root1->right, root2->right);

        return root3;
    }

    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        return merge(root1, root2);
    }
};

Merge Bsts To Create Single Bst Solution Code

1