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 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
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.
- Number of subtrees having odd count of even numbers
- Count of subtrees in a Binary Tree having XOR value K
- Count of subtrees in a Binary Tree having bitwise OR value K
- Convert left-right representation of a binary tree to down-right
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find largest subtree sum in a tree
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Count of nodes having odd divisors in the given subtree for Q queries
- Node having maximum number of nodes less than its value in its subtree
- Find Count of Single Valued Subtrees
- Find All Duplicate Subtrees
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- Calculate number of nodes in all subtrees | Using DFS
- Count subtrees that sum up to a given value x only using single recursive function
- Subtrees formed after bursting nodes
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Count of subtrees from an N-ary tree consisting of single colored nodes