Given a binary tree, find all duplicate subtrees. For each duplicate subtrees, we only need to return the root node of any one of them. Two trees are duplicate if they have the same structure with same node values.
Input : 1 / \ 2 3 / / \ 4 2 4 / 4 Output : 2 / and 4 4 Explanation: Above Trees are two duplicate subtrees. Therefore, you need to return above trees root in the form of a list.
The idea is to use hashing. We store inorder traversals of subtrees in a hash. Since simple inorder traversal cannot uniquely identify a tree, we use symbols like ‘(‘ and ‘)’ to represent NULL nodes.
We pass a Unordered Map in C++ as an argument to the helper function which recursively calculates inorder string and increases its count in map. If any string gets repeated, then it will imply duplication of the subtree rooted at that node so push that node in Final result and return the vector of these nodes.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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 contains duplicate subtrees of size 2 or more
- Calculate number of nodes in all subtrees | Using DFS
- Find Count of Single Valued Subtrees
- Find largest subtree having identical left and right subtrees
- Number of subtrees having odd count of even numbers
- Count subtrees that sum up to a given value x only using single recursive function
- Subtrees formed after bursting nodes
- Count of subtrees in a Binary Tree having XOR value K
- Count of subtrees in a Binary Tree having bitwise OR value K
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Java program to print all duplicate characters in a string
- Find the smallest subarray having atleast one duplicate
- Check if a given array contains duplicate elements within k distance from each other
- AVL with duplicate keys
- Check if a Binary Tree (not BST) has duplicate values
- Replace duplicates with greater than previous duplicate value
- Count the nodes of a tree whose weighted string does not contain any duplicate characters
- Duplicate subtree in Binary Tree | SET 2
- Print all Strings from array A having all strings from array B as subsequence