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
- 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 the Kth node in the DFS traversal of a given subtree in a Tree
- Find sum of all left leaves in a given Binary Tree
- Subtrees formed after bursting nodes
- Calculate number of nodes in all subtrees | Using DFS
- Number of subtrees having odd count of even numbers
- 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
- Subtree with given sum in a Binary Tree
Improved By : PranchalKatiyar