Given a Binary Tree, check whether the Binary tree contains a duplicate sub-tree of size 2 or more.
Note : Two same leaf nodes are not considered as subtree size of a leaf node is one.
Input : Binary Tree A / \ B C / \ \ D E B / \ D E Output : Yes
Asked in : Google Interview
[ Method 1]
A simple solution is that, we pick every node of tree and try to find is any sub-tree of given tree is present in tree which is identical with that sub-tree. Here we can use below post to find if a subtree is present anywhere else in tree.
Check if a binary tree is subtree of another binary tree
[Method 2 ]( Efficient solution )
An Efficient solution based on tree serialization and hashing. The idea is to serialize subtrees as strings and store the strings in hash table. Once we find a serialized tree (which is not a leaf) already existing in hash-table, we return true.
Below The implementation of above idea.
This article is contributed by Nishant Singh. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if a Binary Tree (not BST) has duplicate values
- Find All Duplicate Subtrees
- Duplicate subtree in Binary Tree | SET 2
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check whether a given binary tree is skewed binary tree or not?
- Check if a binary tree is subtree of another binary tree | Set 1
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree | Set 2
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Check if the given n-ary tree is a binary tree
- Check whether a given binary tree is perfect or not
- Check if a given Binary Tree is SumTree