# Find All Duplicate Subtrees

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.

Examples:

```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.
```

## Recommended: Please solve it on PRACTICE first, before moving on to the solution.

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.

## C++

 `// C++ program to find averages of all levels ` `// in a binary tree. ` `#include ` `using` `namespace` `std; ` ` `  `/* A binary tree node has data, pointer to ` `left child and a pointer to right child */` `struct` `Node { ` `    ``int` `data; ` `    ``struct` `Node* left, *right; ` `}; ` ` `  `string inorder(Node* node, unordered_map& m) ` `{ ` `    ``if` `(!node) ` `        ``return` `""``; ` ` `  `    ``string str = ``"("``; ` `    ``str += inorder(node->left, m); ` `    ``str += to_string(node->data); ` `    ``str += inorder(node->right, m); ` `    ``str += ``")"``; ` ` `  `    ``// Subtree already present (Note that we use ` `    ``// unordered_map instead of unordered_set ` `    ``// because we want to print multiple duplicates ` `    ``// only once, consider example of 4 in above ` `    ``// subtree, it should be printed only once. ` `    ``if` `(m[str] == 1) ` `        ``cout << node->data << ``" "``; ` ` `  `    ``m[str]++; ` ` `  `    ``return` `str; ` `} ` ` `  `// Wrapper over inorder() ` `void` `printAllDups(Node* root) ` `{ ` `    ``unordered_map m; ` `    ``inorder(root, m); ` `} ` ` `  `/* Helper function that allocates a ` `new node with the given data and ` `NULL left and right pointers. */` `Node* newNode(``int` `data) ` `{ ` `    ``Node* temp = ``new` `Node; ` `    ``temp->data = data; ` `    ``temp->left = temp->right = NULL; ` `    ``return` `temp; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``Node* root = NULL; ` `    ``root = newNode(1); ` `    ``root->left = newNode(2); ` `    ``root->right = newNode(3); ` `    ``root->left->left = newNode(4); ` `    ``root->right->left = newNode(2); ` `    ``root->right->left->left = newNode(4); ` `    ``root->right->right = newNode(4); ` `    ``printAllDups(root); ` `    ``return` `0; ` `} `

## Java

 `// A java program to find all duplicate subtrees  ` `// in a binary tree. ` `import` `java.util.HashMap; ` `public` `class` `Duplicate_subtress { ` ` `  `    ``/* A binary tree node has data, pointer to ` `    ``left child and a pointer to right child */` `    ``static` `HashMap m; ` `    ``static` `class` `Node { ` `        ``int` `data; ` `        ``Node left; ` `        ``Node right; ` `        ``Node(``int` `data){ ` `            ``this``.data = data; ` `            ``left = ``null``; ` `            ``right = ``null``; ` `        ``} ` `    ``} ` `    ``static` `String inorder(Node node) ` `    ``{ ` `        ``if` `(node == ``null``) ` `            ``return` `""``; ` `      `  `        ``String str = ``"("``; ` `        ``str += inorder(node.left); ` `        ``str += Integer.toString(node.data); ` `        ``str += inorder(node.right); ` `        ``str += ``")"``; ` `      `  `        ``// Subtree already present (Note that we use ` `        ``// HashMap instead of HashSet ` `        ``// because we want to print multiple duplicates ` `        ``// only once, consider example of 4 in above ` `        ``// subtree, it should be printed only once.        ` `        ``if` `(m.get(str) != ``null` `&& m.get(str)==``1` `) ` `            ``System.out.print( node.data + ``" "``); ` `      `  `        ``if` `(m.containsKey(str)) ` `            ``m.put(str, m.get(str) + ``1``); ` `        ``else` `            ``m.put(str, ``1``); ` `         `  `        `  `        ``return` `str; ` `    ``} ` `      `  `    ``// Wrapper over inorder() ` `    ``static` `void` `printAllDups(Node root) ` `    ``{ ` `        ``m = ``new` `HashMap<>(); ` `        ``inorder(root); ` `    ``}  ` `    ``// Driver code ` `    ``public` `static` `void` `main(String args[]) ` `    ``{ ` `        ``Node root = ``null``; ` `        ``root = ``new` `Node(``1``); ` `        ``root.left = ``new` `Node(``2``); ` `        ``root.right = ``new` `Node(``3``); ` `        ``root.left.left = ``new` `Node(``4``); ` `        ``root.right.left = ``new` `Node(``2``); ` `        ``root.right.left.left = ``new` `Node(``4``); ` `        ``root.right.right = ``new` `Node(``4``); ` `        ``printAllDups(root); ` `    ``} ` `} ` `// This code is contributed by Sumit Ghosh `

## Python3

 `# Python3 program to find averages of  ` `# all levels in a binary tree.  ` ` `  `# Helper function that allocates a  ` `# new node with the given data and  ` `# None left and right pointers.  ` `class` `newNode: ` `    ``def` `__init__(``self``, data): ` `        ``self``.data ``=` `data  ` `        ``self``.left ``=` `self``.right ``=` `None` ` `  `def` `inorder(node, m): ` `    ``if` `(``not` `node):  ` `        ``return` `""  ` ` `  `    ``Str` `=` `"("` `    ``Str` `+``=` `inorder(node.left, m)  ` `    ``Str` `+``=` `str``(node.data)  ` `    ``Str` `+``=` `inorder(node.right, m)  ` `    ``Str` `+``=` `")"` ` `  `    ``# Subtree already present (Note that  ` `    ``# we use unordered_map instead of  ` `    ``# unordered_set because we want to print ` `    ``# multiple duplicates only once, consider  ` `    ``# example of 4 in above subtree, it  ` `    ``# should be printed only once.  ` `    ``if` `(``Str` `in` `m ``and` `m[``Str``] ``=``=` `1``):  ` `        ``print``(node.data, end ``=` `" "``)  ` `    ``if` `Str` `in` `m: ` `        ``m[``Str``] ``+``=` `1` `    ``else``: ` `        ``m[``Str``] ``=` `1` ` `  `    ``return` `Str` ` `  `# Wrapper over inorder()  ` `def` `printAllDups(root): ` `    ``m ``=` `{}  ` `    ``inorder(root, m) ` ` `  `# Driver code  ` `if` `__name__ ``=``=` `'__main__'``: ` `    ``root ``=` `None` `    ``root ``=` `newNode(``1``)  ` `    ``root.left ``=` `newNode(``2``)  ` `    ``root.right ``=` `newNode(``3``)  ` `    ``root.left.left ``=` `newNode(``4``)  ` `    ``root.right.left ``=` `newNode(``2``)  ` `    ``root.right.left.left ``=` `newNode(``4``)  ` `    ``root.right.right ``=` `newNode(``4``)  ` `    ``printAllDups(root)  ` ` `  `# This code is contributed by PranchalK `

## C#

 `// A C# program to find all duplicate subtrees  ` `// in a binary tree. ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG  ` `{ ` ` `  `    ``/* A binary tree node has data, pointer to ` `    ``left child and a pointer to right child */` `    ``static` `Dictionary m = ``new` `Dictionary(); ` `    ``public` `class` `Node  ` `    ``{ ` `        ``public` `int` `data; ` `        ``public` `Node left; ` `        ``public` `Node right; ` `        ``public` `Node(``int` `data) ` `        ``{ ` `            ``this``.data = data; ` `            ``left = ``null``; ` `            ``right = ``null``; ` `        ``} ` `    ``} ` `     `  `    ``static` `String inorder(Node node) ` `    ``{ ` `        ``if` `(node == ``null``) ` `            ``return` `""``; ` `     `  `        ``String str = ``"("``; ` `        ``str += inorder(node.left); ` `        ``str += (node.data).ToString(); ` `        ``str += inorder(node.right); ` `        ``str += ``")"``; ` `     `  `        ``// Subtree already present (Note that we use ` `        ``// HashMap instead of HashSet ` `        ``// because we want to print multiple duplicates ` `        ``// only once, consider example of 4 in above ` `        ``// subtree, it should be printed only once.      ` `        ``if` `(m.ContainsKey(str) && m[str] == 1 ) ` `            ``Console.Write(node.data + ``" "``); ` `     `  `        ``if` `(m.ContainsKey(str)) ` `            ``m[str] = m[str] + 1; ` `        ``else` `            ``m.Add(str, 1); ` `         `  `        ``return` `str; ` `    ``} ` `     `  `    ``// Wrapper over inorder() ` `    ``static` `void` `printAllDups(Node root) ` `    ``{ ` `        ``m = ``new` `Dictionary(); ` `        ``inorder(root); ` `    ``}  ` `     `  `    ``// Driver code ` `    ``public` `static` `void` `Main(String []args) ` `    ``{ ` `        ``Node root = ``null``; ` `        ``root = ``new` `Node(1); ` `        ``root.left = ``new` `Node(2); ` `        ``root.right = ``new` `Node(3); ` `        ``root.left.left = ``new` `Node(4); ` `        ``root.right.left = ``new` `Node(2); ` `        ``root.right.left.left = ``new` `Node(4); ` `        ``root.right.right = ``new` `Node(4); ` `        ``printAllDups(root); ` `    ``} ` `} ` ` `  `// This code is contributed by Princi Singh `

Output:

```4 2
```

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

7

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.