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 the node with minimum value in a Binary Search Tree
- Write Code to Determine if Two Trees are Identical
- Write a Program to Find the Maximum Depth or Height of a Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 1
- Find the maximum sum leaf to root path in a Binary Tree
- Largest Independent Set Problem | DP-26
- Find multiplication of sums of data of leaves at same levels
- Iterative Method to find Height of Binary Tree
- Find depth of the deepest odd level leaf node
- Print Left View of a Binary Tree
- Deepest left leaf node in a binary tree
- Find next right node of a given key
- Find LCA in Binary Tree using RMQ
- Find distance between two nodes of a Binary Tree
Improved By : PranchalKatiyar