Giventwo 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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to append nodes of BST1 into set.voidappendNodes(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.boolcheckNodes(Node*root,unordered_set<int>&s){if(root==nullptr)returntrue;// If current node does not exist in // set, then return false.if(s.find(root->data)==s.end())returnfalse;// Remove the value from the set s.erase(root->data);// Recursively check the left and // right subtrees.returncheckNodes(root->left,s)&&checkNodes(root->right,s);}// Main function to compare two BST.boolcheckBSTs(Node*root1,Node*root2){// append node values into set.unordered_set<int>s;appendNodes(root1,s);// Check nodes of BST2boolans=checkNodes(root2,s);// If BST2 does not contain all values// of BST1if(ans==false)returnfalse;// If BST2 still contains any value, // then return false. Otherwise return // true.returns.empty()==true;}intmain(){// Tree 1// 15// / \ // 10 20// / \ \ // 5 12 25Node*root1=newNode(15);root1->left=newNode(10);root1->right=newNode(20);root1->left->left=newNode(5);root1->left->right=newNode(12);root1->right->right=newNode(25);// Tree 2// 15// / \ // 12 20// / \ // 5 25// \ // 10Node*root2=newNode(15);root2->left=newNode(12);root2->right=newNode(20);root2->left->left=newNode(5);root2->left->left->right=newNode(10);root2->right->right=newNode(25);if(checkBSTs(root1,root2)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
Java
// Java program to check if two // BSTs contain same set of elementsimportjava.util.HashSet;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to append nodes of BST1 into set.staticvoidappendNodes(Noderoot,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.staticbooleancheckNodes(Noderoot,HashSet<Integer>s){if(root==null)returntrue;// If current node does not exist in // set, then return false.if(!s.contains(root.data))returnfalse;// Remove the value from the sets.remove(root.data);// Recursively check the left and // right subtrees.returncheckNodes(root.left,s)&&checkNodes(root.right,s);}// Main function to compare two BST.staticbooleancheckBSTs(Noderoot1,Noderoot2){// Append node values into set.HashSet<Integer>s=newHashSet<>();appendNodes(root1,s);// Check nodes of BST2booleanans=checkNodes(root2,s);// If BST2 does not contain all values// of BST1if(!ans)returnfalse;// If BST2 still contains any value, // then return false. Otherwise return // true.returns.isEmpty();}publicstaticvoidmain(String[]args){// Tree 1// 15// / \// 10 20// / \ \// 5 12 25Noderoot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10Noderoot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(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 elementsclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to append nodes of BST1 into set.defappendNodes(root,s):ifrootisNone:returns.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.defcheckNodes(root,s):ifrootisNone:returnTrue# If current node does not exist in # set, then return false.ifroot.datanotins:returnFalse# Remove the value from the set s.remove(root.data)# Recursively check the left and # right subtrees.returncheckNodes(root.left,s)and \
checkNodes(root.right,s)defcheckBSTs(root1,root2):# Append node values into set.s=set()appendNodes(root1,s)# Check nodes of BST2ans=checkNodes(root2,s)# If BST2 does not contain all values# of BST1ifnotans:returnFalse# If BST2 still contains any value, # then return false. Otherwise return # true.returnlen(s)==0if__name__=="__main__":# Tree 1# 15# / \# 10 20# / \ \# 5 12 25root1=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# \# 10root2=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)ifcheckBSTs(root1,root2):print("True")else:print("False")
C#
// C# program to check if two // BSTs contain same set of elementsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to append nodes of BST1 into set.staticvoidappendNodes(Noderoot,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.staticboolcheckNodes(Noderoot,HashSet<int>s){if(root==null)returntrue;// If current node does not exist in // set, then return false.if(!s.Contains(root.data))returnfalse;// Remove the value from the sets.Remove(root.data);// Recursively check the left and // right subtrees.returncheckNodes(root.left,s)&&checkNodes(root.right,s);}// Main function to compare two BST.staticboolcheckBSTs(Noderoot1,Noderoot2){// Append node values into set.HashSet<int>s=newHashSet<int>();appendNodes(root1,s);// Check nodes of BST2boolans=checkNodes(root2,s);// If BST2 does not contain all values// of BST1if(!ans)returnfalse;// If BST2 still contains any value, // then return false. Otherwise return // true.returns.Count==0;}staticvoidMain(string[]args){// Tree 1// 15// / \// 10 20// / \ \// 5 12 25Noderoot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10Noderoot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(25);if(checkBSTs(root1,root2)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to check if two // BSTs contain same set of elementsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to append nodes of BST1 into set.functionappendNodes(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.functioncheckNodes(root,s){if(root===null)returntrue;// If current node does not exist in // set, then return false.if(!s.has(root.data))returnfalse;// Remove the value from the set s.delete(root.data);// Recursively check the left and // right subtrees.returncheckNodes(root.left,s)&&checkNodes(root.right,s);}// Main function to compare two BST.functioncheckBSTs(root1,root2){// Append node values into set.lets=newSet();appendNodes(root1,s);// Check nodes of BST2letans=checkNodes(root2,s);// If BST2 does not contain all values// of BST1if(!ans)returnfalse;// If BST2 still contains any value, // then return false. Otherwise return // true.returns.size===0;}// Tree 1// 15// / \// 10 20// / \ \// 5 12 25letroot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10letroot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// In-order function to append // nodes of BST into arrayvoidappendNodes(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.boolcheckBSTs(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())returnfalse;for(inti=0;i<arr1.size();i++){// If elements do not match,// return false.if(arr1[i]!=arr2[i])returnfalse;}returntrue;}intmain(){// Tree 1// 15// / \ // 10 20// / \ \ // 5 12 25Node*root1=newNode(15);root1->left=newNode(10);root1->right=newNode(20);root1->left->left=newNode(5);root1->left->right=newNode(12);root1->right->right=newNode(25);// Tree 2// 15// / \ // 12 20// / \ // 5 25// \ // 10Node*root2=newNode(15);root2->left=newNode(12);root2->right=newNode(20);root2->left->left=newNode(5);root2->left->left->right=newNode(10);root2->right->right=newNode(25);if(checkBSTs(root1,root2)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
Java
// Java program to check if two // BSTs contain same set of elementsimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// In-order function to append // nodes of BST into arraystaticvoidappendNodes(Noderoot,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.staticbooleancheckBSTs(Noderoot1,Noderoot2){ArrayList<Integer>arr1=newArrayList<>();ArrayList<Integer>arr2=newArrayList<>();appendNodes(root1,arr1);appendNodes(root2,arr2);// If size of two arrays is not // same, return false.if(arr1.size()!=arr2.size())returnfalse;for(inti=0;i<arr1.size();i++){// If elements do not match,// return false.if(!arr1.get(i).equals(arr2.get(i)))returnfalse;}returntrue;}publicstaticvoidmain(String[]args){// Tree 1// 15// / \// 10 20// / \ \// 5 12 25Noderoot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10Noderoot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(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 elementsclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# In-order function to append # nodes of BST into arraydefappendNodes(root,arr):ifrootisNone:returnappendNodes(root.left,arr)arr.append(root.data)appendNodes(root.right,arr)# Main function to compare two BST.defcheckBSTs(root1,root2):arr1,arr2=[],[]appendNodes(root1,arr1)appendNodes(root2,arr2)# If size of two arrays is not # same, return false.iflen(arr1)!=len(arr2):returnFalseforiinrange(len(arr1)):# If elements do not match,# return false.ifarr1[i]!=arr2[i]:returnFalsereturnTrueif__name__=="__main__":# Tree 1# 15# / \# 10 20# / \ \# 5 12 25root1=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# \# 10root2=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)ifcheckBSTs(root1,root2):print("True")else:print("False")
C#
// C# program to check if two // BSTs contain same set of elementsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// In-order function to append // nodes of BST into arraystaticvoidappendNodes(Noderoot,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.staticboolcheckBSTs(Noderoot1,Noderoot2){List<int>arr1=newList<int>();List<int>arr2=newList<int>();appendNodes(root1,arr1);appendNodes(root2,arr2);// If size of two arrays is not // same, return false.if(arr1.Count!=arr2.Count)returnfalse;for(inti=0;i<arr1.Count;i++){// If elements do not match,// return false.if(arr1[i]!=arr2[i])returnfalse;}returntrue;}staticvoidMain(){// Tree 1// 15// / \// 10 20// / \ \// 5 12 25Noderoot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10Noderoot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(25);if(checkBSTs(root1,root2)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to check if two // BSTs contain same set of elementsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// In-order function to append // nodes of BST into arrayfunctionappendNodes(root,arr){if(root===null)return;appendNodes(root.left,arr);arr.push(root.data);appendNodes(root.right,arr);}// Main function to compare two BST.functioncheckBSTs(root1,root2){letarr1=[],arr2=[];appendNodes(root1,arr1);appendNodes(root2,arr2);// If size of two arrays is not // same, return false.if(arr1.length!==arr2.length)returnfalse;for(leti=0;i<arr1.length;i++){// If elements do not match,// return false.if(arr1[i]!==arr2[i])returnfalse;}returntrue;}// Tree 1// 15// / \// 10 20// / \ \// 5 12 25letroot1=newNode(15);root1.left=newNode(10);root1.right=newNode(20);root1.left.left=newNode(5);root1.left.right=newNode(12);root1.right.right=newNode(25);// Tree 2// 15// / \// 12 20// / \// 5 25// \// 10letroot2=newNode(15);root2.left=newNode(12);root2.right=newNode(20);root2.left.left=newNode(5);root2.left.left.right=newNode(10);root2.right.right=newNode(25);if(checkBSTs(root1,root2)){console.log("True");}else{console.log("False");}