Open In App

Check if two BSTs contain same set of elements

Last Updated : 22 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two Binary Search Trees consisting of unique positive elements, the task is to check whether the two BSTs contain the same set of elements or not. The structure of the two given BSTs can be different. 

Example:

Input:

check-if-two-bsts-contain-same-set-of-elements


Output: True
Explanation: The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25}

The simple idea is to traverse the first tree. For each node, check if a node exists with the same value in the second tree. If it exists, then set the node value of the second tree to -1 (to mark the node as visited) and recursively check for the left and right subtree. Otherwise, return false. Finally, check if all the nodes of the second tree have a value of -1.

Time Complexity: O( n * n ), where n is the number of nodes in the BST. 
Auxiliary Space: O( h1 + h2 ), where h1 and h2 are the heights of the two trees.

[Expected Approach - 1] Using Recursion and hash set - O(n) Time and O(n) Space

The idea is to store the node values of the first BST in a hashSet. Then, traverse the second BST and check for every node if its value exists in the hashSet. If it exists, then remove the value from the hash set and recursively check for left and right subtree. Otherwise, return false. Finally check if the hash set is empty or not.

Below is the implementation of the above approach: 

C++
// C++ program to check if two 
// BSTs contain same set of elements
#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 append nodes of BST1 into set.
void appendNodes(Node* root, unordered_set<int> &s) {
    if (root == nullptr) return;
    
    s.insert(root->data);
    appendNodes(root->left, s);
    appendNodes(root->right, s);
}

// Recursive function to check if each
// node of BST2 exists in BST1 or not.
bool checkNodes(Node* root, unordered_set<int> &s) {
    if (root == nullptr) return true;
    
    // If current node does not exist in 
    // set, then return false.
    if (s.find(root->data) == s.end()) 
        return false;
    
    // Remove the value from the set     
    s.erase(root->data);
    
    // Recursively check the left and 
    // right subtrees.
    return 
    checkNodes(root->left, s)
    &&
    checkNodes(root->right, s);
}

// Main function to compare two BST.
bool checkBSTs(Node* root1, Node* root2) {
    
    // append node values into set.
    unordered_set<int> s;
    appendNodes(root1, s);
    
    // Check nodes of BST2
    bool ans = checkNodes(root2, s);
    
    // If BST2 does not contain all values
    // of BST1
    if (ans == false) 
        return false;
    
    // If BST2 still contains any value, 
    // then return false. Otherwise return 
    // true.
    return s.empty() == true;
}

int main() {
    
    // Tree 1
    //         15
    //        /  \
    //      10    20
    //     /  \     \
    //    5   12     25
    Node* root1 = new Node(15);
    root1->left = new Node(10);
    root1->right = new Node(20);
    root1->left->left = new Node(5);
    root1->left->right = new Node(12);
    root1->right->right = new Node(25);
    
    // Tree 2
    //         15
    //        /  \
    //      12    20
    //     /       \
    //    5         25
    //     \
    //     10
    Node* root2 = new Node(15);
    root2->left = new Node(12);
    root2->right = new Node(20);
    root2->left->left = new Node(5);
    root2->left->left->right = new Node(10);
    root2->right->right = new Node(25);
    
    if (checkBSTs(root1, root2)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    return 0;
}
Java
// Java program to check if two 
// BSTs contain same set of elements
import java.util.HashSet;

class Node {
    int data;
    Node left, right;

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

class GfG {

    // Function to append nodes of BST1 into set.
    static void appendNodes(Node root, HashSet<Integer> s) {
        if (root == null) return;

        s.add(root.data);
        appendNodes(root.left, s);
        appendNodes(root.right, s);
    }

    // Recursive function to check if each
    // node of BST2 exists in BST1 or not.
    static boolean checkNodes(Node root, HashSet<Integer> s) {
        if (root == null) return true;

        // If current node does not exist in 
        // set, then return false.
        if (!s.contains(root.data)) 
            return false;

        // Remove the value from the set
        s.remove(root.data);

        // Recursively check the left and 
        // right subtrees.
        return checkNodes(root.left, s) && checkNodes(root.right, s);
    }

    // Main function to compare two BST.
    static boolean checkBSTs(Node root1, Node root2) {
        
        // Append node values into set.
        HashSet<Integer> s = new HashSet<>();
        appendNodes(root1, s);

        // Check nodes of BST2
        boolean ans = checkNodes(root2, s);

        // If BST2 does not contain all values
        // of BST1
        if (!ans)
            return false;

        // If BST2 still contains any value, 
        // then return false. Otherwise return 
        // true.
        return s.isEmpty();
    }

    public static void main(String[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check if two 
# BSTs contain same set of elements

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to append nodes of BST1 into set.
def appendNodes(root, s):
    if root is None:
        return
    
    s.add(root.data)
    appendNodes(root.left, s)
    appendNodes(root.right, s)

# Recursive function to check if each
# node of BST2 exists in BST1 or not.
def checkNodes(root, s):
    if root is None:
        return True

    # If current node does not exist in 
    # set, then return false.
    if root.data not in s:
        return False
    
    # Remove the value from the set     
    s.remove(root.data)
    
    # Recursively check the left and 
    # right subtrees.
    return checkNodes(root.left, s) and \
  	checkNodes(root.right, s)

def checkBSTs(root1, root2):
    
    # Append node values into set.
    s = set()
    appendNodes(root1, s)
    
    # Check nodes of BST2
    ans = checkNodes(root2, s)
    
    # If BST2 does not contain all values
    # of BST1
    if not ans:
        return False
    
    # If BST2 still contains any value, 
    # then return false. Otherwise return 
    # true.
    return len(s) == 0

if __name__ == "__main__":
    
    # Tree 1
    #         15
    #        /  \
    #      10    20
    #     /  \     \
    #    5   12     25
    root1 = Node(15)
    root1.left = Node(10)
    root1.right = Node(20)
    root1.left.left = Node(5)
    root1.left.right = Node(12)
    root1.right.right = Node(25)
    
    # Tree 2
    #         15
    #        /  \
    #      12    20
    #     /       \
    #    5         25
    #     \
    #     10
    root2 = Node(15)
    root2.left = Node(12)
    root2.right = Node(20)
    root2.left.left = Node(5)
    root2.left.left.right = Node(10)
    root2.right.right = Node(25)
    
    if checkBSTs(root1, root2):
        print("True")
    else:
        print("False")
C#
// C# program to check if two 
// BSTs contain same set of elements
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 append nodes of BST1 into set.
    static void appendNodes(Node root, HashSet<int> s) {
        if (root == null) return;

        s.Add(root.data);
        appendNodes(root.left, s);
        appendNodes(root.right, s);
    }

    // Recursive function to check if each
    // node of BST2 exists in BST1 or not.
    static bool checkNodes(Node root, HashSet<int> s) {
        if (root == null) return true;

        // If current node does not exist in 
        // set, then return false.
        if (!s.Contains(root.data)) 
            return false;

        // Remove the value from the set
        s.Remove(root.data);

        // Recursively check the left and 
        // right subtrees.
        return checkNodes(root.left, s) 
          		&& checkNodes(root.right, s);
    }

    // Main function to compare two BST.
    static bool checkBSTs(Node root1, Node root2) {
      
        // Append node values into set.
        HashSet<int> s = new HashSet<int>();
        appendNodes(root1, s);

        // Check nodes of BST2
        bool ans = checkNodes(root2, s);

        // If BST2 does not contain all values
        // of BST1
        if (!ans)
            return false;

        // If BST2 still contains any value, 
        // then return false. Otherwise return 
        // true.
        return s.Count == 0;
    }

    static void Main(string[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check if two 
// BSTs contain same set of elements

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to append nodes of BST1 into set.
function appendNodes(root, s) {
    if (root === null) return;

    s.add(root.data);
    appendNodes(root.left, s);
    appendNodes(root.right, s);
}

// Recursive function to check if each
// node of BST2 exists in BST1 or not.
function checkNodes(root, s) {
    if (root === null) return true;

    // If current node does not exist in 
    // set, then return false.
    if (!s.has(root.data)) 
        return false;

    // Remove the value from the set     
    s.delete(root.data);

    // Recursively check the left and 
    // right subtrees.
    return checkNodes(root.left, s) 
    		&& checkNodes(root.right, s);
}

// Main function to compare two BST.
function checkBSTs(root1, root2) {
    
    // Append node values into set.
    let s = new Set();
    appendNodes(root1, s);

    // Check nodes of BST2
    let ans = checkNodes(root2, s);

    // If BST2 does not contain all values
    // of BST1
    if (!ans)
        return false;

    // If BST2 still contains any value, 
    // then return false. Otherwise return 
    // true.
    return s.size === 0;
}

// Tree 1
//         15
//        /  \
//      10    20
//     /  \     \
//    5   12     25
let root1 = new Node(15);
root1.left = new Node(10);
root1.right = new Node(20);
root1.left.left = new Node(5);
root1.left.right = new Node(12);
root1.right.right = new Node(25);

// Tree 2
//         15
//        /  \
//      12    20
//     /       \
//    5         25
//     \
//     10
let root2 = new Node(15);
root2.left = new Node(12);
root2.right = new Node(20);
root2.left.left = new Node(5);
root2.left.left.right = new Node(10);
root2.right.right = new Node(25);

if (checkBSTs(root1, root2)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Note: If BST's does not contain distinct elements, then this approach can be implemented using hashmap instead of hash set.

[Expected Approach - 2] Using In-Order Traversal and Array - O(n) Time and O(n) Space

The idea is to use the property of BST that in-order traversal of a BST generates a sorted array. So, traverse the trees and generate two arrays. If the two arrays are same, then the BST's have same set of elements, so return true. Otherwise return false.

Below is the implementation of the above approach: 

C++
// C++ program to check if two 
// BSTs contain same set of elements
#include <bits/stdc++.h>
using namespace std;

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

// In-order function to append 
// nodes of BST into array
void appendNodes(Node* root, vector<int> &arr) {
    if (root == nullptr) return;
    
    appendNodes(root->left, arr);
    arr.push_back(root->data);
    appendNodes(root->right, arr);
}

// Main function to compare two BST.
bool checkBSTs(Node* root1, Node* root2) {
    
    vector<int> arr1, arr2;
    appendNodes(root1, arr1);
    appendNodes(root2, arr2);
    
    // If size of two arrays is not 
    // same, return false.
    if (arr1.size() != arr2.size())
        return false;
        
    for (int i=0; i<arr1.size(); i++) {
        
        // If elements do not match,
        // return false.
        if (arr1[i] != arr2[i]) 
            return false;
    }
    
    return true;
}

int main() {
    
    // Tree 1
    //         15
    //        /  \
    //      10    20
    //     /  \     \
    //    5   12     25
    Node* root1 = new Node(15);
    root1->left = new Node(10);
    root1->right = new Node(20);
    root1->left->left = new Node(5);
    root1->left->right = new Node(12);
    root1->right->right = new Node(25);
    
    // Tree 2
    //         15
    //        /  \
    //      12    20
    //     /       \
    //    5         25
    //     \
    //     10
    Node* root2 = new Node(15);
    root2->left = new Node(12);
    root2->right = new Node(20);
    root2->left->left = new Node(5);
    root2->left->left->right = new Node(10);
    root2->right->right = new Node(25);
    
    if (checkBSTs(root1, root2)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    return 0;
}
Java
// Java program to check if two 
// BSTs contain same set of elements
import java.util.ArrayList;

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

class GfG {

    // In-order function to append 
    // nodes of BST into array
    static void appendNodes(Node root, 
                            ArrayList<Integer> arr) {
        if (root == null) return;
        
        appendNodes(root.left, arr);
        arr.add(root.data);
        appendNodes(root.right, arr);
    }

    // Main function to compare two BST.
    static boolean checkBSTs(Node root1, Node root2) {
        ArrayList<Integer> arr1 = new ArrayList<>();
        ArrayList<Integer> arr2 = new ArrayList<>();
        appendNodes(root1, arr1);
        appendNodes(root2, arr2);

        // If size of two arrays is not 
        // same, return false.
        if (arr1.size() != arr2.size()) return false;
        
        for (int i = 0; i < arr1.size(); i++) {

            // If elements do not match,
            // return false.
            if (!arr1.get(i).equals(arr2.get(i))) 
                return false;
        }
        return true;
    }

    public static void main(String[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check if two 
# BSTs contain same set of elements

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# In-order function to append 
# nodes of BST into array
def appendNodes(root, arr):
    if root is None:
        return
    
    appendNodes(root.left, arr)
    arr.append(root.data)
    appendNodes(root.right, arr)

# Main function to compare two BST.
def checkBSTs(root1, root2):
    arr1, arr2 = [], []
    appendNodes(root1, arr1)
    appendNodes(root2, arr2)
    
    # If size of two arrays is not 
    # same, return false.
    if len(arr1) != len(arr2):
        return False
    
    for i in range(len(arr1)):
      
        # If elements do not match,
        # return false.
        if arr1[i] != arr2[i]:
            return False
    
    return True

if __name__ == "__main__":
    
    # Tree 1
    #         15
    #        /  \
    #      10    20
    #     /  \     \
    #    5   12     25
    root1 = Node(15)
    root1.left = Node(10)
    root1.right = Node(20)
    root1.left.left = Node(5)
    root1.left.right = Node(12)
    root1.right.right = Node(25)
    
    # Tree 2
    #         15
    #        /  \
    #      12    20
    #     /       \
    #    5         25
    #     \
    #     10
    root2 = Node(15)
    root2.left = Node(12)
    root2.right = Node(20)
    root2.left.left = Node(5)
    root2.left.left.right = Node(10)
    root2.right.right = Node(25)
    
    if checkBSTs(root1, root2):
        print("True")
    else:
        print("False")
C#
// C# program to check if two 
// BSTs contain same set of elements
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 {

    // In-order function to append 
    // nodes of BST into array
    static void appendNodes(Node root, List<int> arr) {
        if (root == null) return;
        
        appendNodes(root.left, arr);
        arr.Add(root.data);
        appendNodes(root.right, arr);
    }

    // Main function to compare two BST.
    static bool checkBSTs(Node root1, Node root2) {
        List<int> arr1 = new List<int>();
        List<int> arr2 = new List<int>();
        appendNodes(root1, arr1);
        appendNodes(root2, arr2);

        // If size of two arrays is not 
        // same, return false.
        if (arr1.Count != arr2.Count) return false;
        
        for (int i = 0; i < arr1.Count; i++) {
            
            // If elements do not match,
            // return false.
            if (arr1[i] != arr2[i]) 
                return false;
        }
        return true;
    }

    static void Main() {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check if two 
// BSTs contain same set of elements

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// In-order function to append 
// nodes of BST into array
function appendNodes(root, arr) {
    if (root === null) return;
    
    appendNodes(root.left, arr);
    arr.push(root.data);
    appendNodes(root.right, arr);
}

// Main function to compare two BST.
function checkBSTs(root1, root2) {
    let arr1 = [], arr2 = [];
    appendNodes(root1, arr1);
    appendNodes(root2, arr2);

    // If size of two arrays is not 
    // same, return false.
    if (arr1.length !== arr2.length) return false;
    
    for (let i = 0; i < arr1.length; i++) {
        
        // If elements do not match,
        // return false.
        if (arr1[i] !== arr2[i]) 
            return false;
    }
    return true;
}

// Tree 1
//         15
//        /  \
//      10    20
//     /  \     \
//    5   12     25
let root1 = new Node(15);
root1.left = new Node(10);
root1.right = new Node(20);
root1.left.left = new Node(5);
root1.left.right = new Node(12);
root1.right.right = new Node(25);

// Tree 2
//         15
//        /  \
//      12    20
//     /       \
//    5         25
//     \
//     10
let root2 = new Node(15);
root2.left = new Node(12);
root2.right = new Node(20);
root2.left.left = new Node(5);
root2.left.left.right = new Node(10);
root2.right.right = new Node(25);

if (checkBSTs(root1, root2)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Check if two BSTs contain same set of elements

Similar Reads