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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Find Count of Single Valued Subtrees
- Find largest subtree having identical left and right subtrees
- Find the smallest subarray having atleast one duplicate
- Count of subtrees in a Binary Tree having XOR value K
- Subtrees formed after bursting nodes
- Calculate number of nodes in all subtrees | Using DFS
- Number of subtrees having odd count of even numbers
- Count subtrees that sum up to a given value x only using single recursive function
- Count of subtrees in a Binary Tree having bitwise OR value K
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- AVL with duplicate keys
- Duplicate subtree in Binary Tree | SET 2
- Replace duplicates with greater than previous duplicate value
- Check if a given array contains duplicate elements within k distance from each other
- Check if a Binary Tree (not BST) has duplicate values
- Count the nodes of a tree whose weighted string does not contain any duplicate characters
- Find four elements that sum to a given value | Set 2
- Find all triplets with zero sum