Given a binary tree, find the largest subtree having identical left and right subtree. Expected complexity is O(n).
Input: 50 / \ 10 60 / \ / \ 5 20 70 70 / \ / \ 65 80 65 80 Output: Largest subtree is rooted at node 60
A simple solution is to consider every node, recursively check if left and right subtrees are identical using the approach discussed here. Keep track of maximum size such node.
We can save recursive calls. The idea is to do a postorder traversal of given binary tree and for each node, we store structure of its left and right subtrees. In order to store the structure of left and right subtree, we use a string. We separate left and right subtree nodes from current node in the string by using a delimiter. For every encountered node, we update largest subtree found so far if its left and right subtree structure are similar.
Below is implementation of above idea –
Largest Subtree is rooted at node 60 and its size is 7
The worst case time complexity still remains O(n2) as we need O(n) time to compare two strings.
We can optimized the space used in above program by using Succinct Encoding of Binary Tree.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 largest subtree sum in a tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find All Duplicate Subtrees
- Find Count of Single Valued Subtrees
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Queries to find the Minimum Weight from a Subtree of atmost D-distant Nodes from Node X
- Find sum of all left leaves in a given Binary Tree
- Subtrees formed after bursting nodes
- Number of subtrees having odd count of even numbers
- Calculate number of nodes in all subtrees | Using DFS
- Count of subtrees in a Binary Tree having XOR value K
- Count of subtrees in a Binary Tree having bitwise OR value K
- Count subtrees that sum up to a given value x only using single recursive function
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- 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