Given the root nodes of the two binary search trees. The task is to print 1 if the two Binary Search Trees are identical else print 0. Two trees are identical if they are identical structurally and nodes have the same values.
In the above images, both Tree1 and Tree2 are identical.
To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.
Below is the step by step algorithm to check if two BSTs are identical:
- If both trees are empty then return 1.
- Else If both trees are non -empty
- Check data of the root nodes (tree1->data == tree2->data)
- Check left subtrees recursively i.e., call sameTree(tree1->left_subtree, tree2->left_subtree)
- Check right subtrees recursively i.e., call sameTree(tree1->right_subtree, tree2->right_subtree)
- If the values returned in the above three steps are true then return 1.
- Else return 0 (one is empty and other is not).
Below is the implementation of the above approach:
Both BSTs are identical
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Check for Identical BSTs without building the trees
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Count the Number of Binary Search Trees present in a Binary Tree
- Merge Two Balanced Binary Search Trees
- Print Common Nodes in Two Binary Search Trees
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Total number of possible Binary Search Trees using Catalan Number
- Check whether two strings are equivalent or not according to given condition
- Construct a Maximum Binary Tree from two given Binary Trees
- Check if an array represents Inorder of Binary Search tree or not
- Binary Search Tree | Set 1 (Search and Insertion)
- Recursive program to insert a star between pair of identical characters
- Check whether BST contains Dead End or not
- Check whether a node is leaf node or not for multiple queries
- Check whether a given number is an ugly number or not
- m-WAY Search Trees | Set-1 ( Searching )
- Check if two trees are mirror of each other using level order traversal
- Check whether every node of binary tree has a value K on itself or its any immediate neighbours
- Binary Tree to Binary Search Tree Conversion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.