• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
June 02, 2022 |760 Views

Check if two BSTs contain same set of elements

Description
Discussion

The most simple method will be to traverse first tree and store its element in a list or array. Now, traverse 2nd tree and simultaneously check if the current element is present in the list or not. 

If yes, then mark the element in the list as negative and check for further elements otherwise if no, then immediately terminate the traversal and print No. 

If all the elements of 2nd tree is present in the list and are marked negative then finally traverse the list to check if there are any non-negative elements left. If Yes then it means that the first tree had some extra element otherwise both trees consist the same set of elements.

This method is an optimization of the above approach. If we observe carefully, we will see that in the above approach, searching for elements in the list takes linear time. We can optimize this operation to be done in constant time using a hashmap instead of a list. 

We insert elements of both trees in different hash sets. Finally, we compare if both hash sets contain the same elements or not.


Check if two BSTs contain same set of elements: https://www.geeksforgeeks.org/check-two-bsts-contain-set-elements/