Given a binary tree, the task is to check whether the binary tree contains a duplicate sub-tree of size two or more.
Input: A / \ B C / \ \ D E B / \ D E Output: Yes B / \ D E is the duplicate sub-tree. Input: A / \ B C / \ D E Output: No
Approach: A DFS based approach has been discussed here. A queue can be used to traverse the tree in a bfs manner. While traversing the nodes, push the node along with its left and right children in a map and if any point the map contains duplicates then the tree contains duplicate sub-trees. For example, if the node is A and its children are B and C then ABC will be pushed to the map. If at any point, ABC has to be pushed again then the tree contains duplicate sub-trees.
Below is the implementation of the above approach:
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.
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find the largest BST subtree in a given Binary Tree | Set 1
- Subtree with given sum in a Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find the largest Complete Subtree in a given Binary Tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the largest Perfect Subtree in a given Binary Tree
- Even size subtree in n-ary tree
- Subtree of all nodes in a tree using DFS
- Euler Tour | Subtree Sum using Segment Tree
- Find largest subtree sum in a tree
- Queries for DFS of a subtree in a tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
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.