Check if two BSTs contain same set of elements
Last Updated : 22 Oct, 2024
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:
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"); }
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"); }
Similar Reads
Binary Search Tree A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the nodeâs value. All nodes in the right subtree of a node contain values s
4 min read
Introduction to Binary Search Tree Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
3 min read
Applications, Advantages and Disadvantages of Binary Search Tree A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST) Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
15 min read
Searching in Binary Search Tree (BST) Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST) Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
10 min read
Balance a Binary Search Tree Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
10 min read
Self-Balancing Binary Search Trees Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read