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 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.
- Find All Duplicate Subtrees
- 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
- Check if the Binary Tree contains a balanced BST of size K
- Count of subtrees from an N-ary tree consisting of single colored nodes
- Check if a Binary Tree (not BST) has duplicate values
- Find Count of Single Valued Subtrees
- Find largest subtree having identical left and right subtrees
- Number of subtrees having odd count of even numbers
- Calculate number of nodes in all subtrees | Using DFS
- Subtrees formed after bursting nodes
- Count subtrees that sum up to a given value x only using single recursive function
- Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Duplicate subtree in Binary Tree | SET 2
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a full binary tree or not | Iterative Approach