VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-two-bsts-contain-set-elements/

⇱ Check if two BSTs contain same set of elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 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: 


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: 


Output
True
Comment