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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above