- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Duplicate Subtrees in C++
Consider we have a binary tree. We have to find if there are some duplicate subtrees in the tree or not. Suppose we have a binary tree like below −
There are two identical subtrees of size 2. In each subtree D, BD and BE both are also duplicate subtrees We can solve this problem by using tree serialization and hashing process. We will store the inorder traversal of subtrees in the hash table. We will insert opening and closing parenthesis for empty nodes.
Example
#include <iostream> #include <unordered_set> #include <unordered_map> #include <algorithm> using namespace std; const char MARKER = '$'; struct Node { public: char data; Node *left, *right; }; Node* getNode(char key) { Node* newNode = new Node; newNode->data = key; newNode->left = newNode->right = NULL; return newNode; } unordered_set<string> subtrees; string inorder(Node* node, unordered_map<string, int>& map) { if (!node) return ""; string str = "("; str += inorder(node->left, map); str += to_string(node->data); str += inorder(node->right, map); str += ")"; if (map[str] == 1) cout << node->data << " "; map[str]++; return str; } void duplicateSubtreeFind(Node *root) { unordered_map<string, int> map; inorder(root, map); } int main() { Node *root = getNode('A'); root->left = getNode('B'); root->right = getNode('C'); root->left->left = getNode('D'); root->left->right = getNode('E'); root->right->right = getNode('B'); root->right->right->right = getNode('E'); root->right->right->left= getNode('D'); duplicateSubtreeFind(root); }
Output
D E B
- Related Articles
- Find Duplicate Subtrees in C++
- Find Count of Single Valued Subtrees in C++
- Check if a Binary Tree contains duplicate subtrees of size 2 or more in C++
- Count Univalue Subtrees in C++
- C# program to find all duplicate elements in an integer array
- Python program to find all duplicate characters in a string
- Java program to find all duplicate characters in a string
- Find All Duplicate Characters from a String using Python
- Count BST subtrees that lie in given range in C++
- Find largest subtree having identical left and right subtrees in Python
- Find all duplicate documents in a MongoDB collection by a key field?
- Sum all duplicate value in array - JavaScript
- Find duplicate rows in a binary matrix in C++
- Sum all duplicate values in array in JavaScript
- Count subtrees that sum up to a given value x in C++

Advertisements