Duplicate subtree in Binary Tree | SET 2
Given a binary tree, the task is to check whether the binary tree contains a duplicate sub-tree of size two or more.
Input:
A
/ \
B C
/ \ \
D E B
/ \
D E
Output: Yes
B
/ \
D E
is the duplicate sub-tree.
Input:
A
/ \
B C
/ \
D E
Output: No
Approach: A DFS based approach has been discussed here. A queue can be used to traverse the tree in a bfs manner. While traversing the nodes, push the node along with its left and right children in a map and if any point the map contains duplicates then the tree contains duplicate sub-trees. For example, if the node is A and its children are B and C then ABC will be pushed to the map. If at any point, ABC has to be pushed again then the tree contains duplicate sub-trees.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
char key;
Node *left, *right;
};
Node* newNode( char key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return node;
}
unordered_set<string> subtrees;
bool dupSubUtil(Node* root)
{
set<string> subtrees;
queue<Node*> bfs;
bfs.push(root);
while (!bfs.empty()) {
Node* n = bfs.front();
bfs.pop();
char l = ' ' , r = ' ' ;
if (n->left != NULL) {
l = n->left->key;
bfs.push(n->left);
}
if (n->right != NULL) {
r = n->right->key;
bfs.push(n->right);
}
string subt;
subt += n->key;
subt += l;
subt += r;
if (l != ' ' || r != ' ' ) {
if (!subtrees.insert(subt).second) {
return true ;
}
}
}
return false ;
}
int main()
{
Node* root = newNode( 'A' );
root->left = newNode( 'B' );
root->right = newNode( 'C' );
root->left->left = newNode( 'D' );
root->left->right = newNode( 'E' );
root->right->right = newNode( 'B' );
root->right->right->right = newNode( 'E' );
root->right->right->left = newNode( 'D' );
cout << (dupSubUtil(root) ? "Yes" : "No" );
return 0;
}
|
Java
import java.util.*;
class Node {
char key;
Node left, right;
Node( char item) {
key = item;
left = right = null ;
}
}
class Main {
static Set<String> subtrees = new HashSet<String>();
static boolean dupSubUtil(Node root) {
Set<String> subtrees = new HashSet<String>();
Queue<Node> bfs = new LinkedList<Node>();
bfs.add(root);
while (!bfs.isEmpty()) {
Node n = bfs.poll();
char l = ' ' , r = ' ' ;
if (n.left != null ) {
l = n.left.key;
bfs.add(n.left);
}
if (n.right != null ) {
r = n.right.key;
bfs.add(n.right);
}
String subt = "" ;
subt += n.key;
subt += l;
subt += r;
if (l != ' ' || r != ' ' ) {
if (!subtrees.add(subt)) {
return true ;
}
}
}
return false ;
}
public static void main(String args[]) {
Node root = new Node( 'A' );
root.left = new Node( 'B' );
root.right = new Node( 'C' );
root.left.left = new Node( 'D' );
root.left.right = new Node( 'E' );
root.right.right = new Node( 'B' );
root.right.right.right = new Node( 'E' );
root.right.right.left = new Node( 'D' );
System.out.println((dupSubUtil(root) ? "Yes" : "No" ));
}
}
|
Python3
class newNode:
def __init__( self , data):
self .key = data
self .left = None
self .right = None
subtrees = set ()
def dupSubUtil(root):
subtrees = set ()
bfs = []
bfs.append(root)
while ( len (bfs)):
n = bfs[ 0 ]
bfs.pop( 0 )
l = ' '
r = ' '
if (n.left ! = None ):
x = n.left
l = x.key
bfs.append(n.left)
if (n.right ! = None ):
x = n.right
r = x.key
bfs.append(n.right)
subt = ""
subt + = n.key
subt + = l
subt + = r
if (l ! = ' ' or r ! = ' ' ):
subtrees.add(subt)
if ( len (subtrees) > 1 ):
return True
return False
root = newNode( 'A' )
root.left = newNode( 'B' )
root.right = newNode( 'C' )
root.left.left = newNode( 'D' )
root.left.right = newNode( 'E' )
root.right.right = newNode( 'B' )
root.right.right.right = newNode( 'E' )
root.right.right.left = newNode( 'D' )
if dupSubUtil(root):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public char key;
public Node left, right;
};
static Node newNode( char key)
{
Node node = new Node();
node.key = key;
node.left = node.right = null ;
return node;
}
static HashSet<String> subtrees = new HashSet<String>();
static bool dupSubUtil(Node root)
{
Queue<Node> bfs = new Queue<Node>();
bfs.Enqueue(root);
while (bfs.Count != 0)
{
Node n = bfs.Peek();
bfs.Dequeue();
char l = ' ' , r = ' ' ;
if (n.left != null )
{
l = n.left.key;
bfs.Enqueue(n.left);
}
if (n.right != null )
{
r = n.right.key;
bfs.Enqueue(n.right);
}
String subt = "" ;
subt += n.key;
subt += l;
subt += r;
if (l != ' ' || r != ' ' )
{
if (!subtrees.Contains(subt))
{
return true ;
}
}
}
return false ;
}
public static void Main(String[] args)
{
Node root = newNode( 'A' );
root.left = newNode( 'B' );
root.right = newNode( 'C' );
root.left.left = newNode( 'D' );
root.left.right = newNode( 'E' );
root.right.right = newNode( 'B' );
root.right.right.right = newNode( 'E' );
root.right.right.left = newNode( 'D' );
if (dupSubUtil(root))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .key = '' ;
this .left = null ;
this .right = null ;
}
};
function newNode(key)
{
var node = new Node();
node.key = key;
node.left = node.right = null ;
return node;
}
var subtrees = new Set();
function dupSubUtil(root)
{
var bfs = [];
bfs.push(root);
while (bfs.length != 0)
{
var n = bfs[0];
bfs.pop();
var l = ' ' , r = ' ' ;
if (n.left != null )
{
l = n.left.key;
bfs.push(n.left);
}
if (n.right != null )
{
r = n.right.key;
bfs.push(n.right);
}
var subt = "" ;
subt += n.key;
subt += l;
subt += r;
if (l != ' ' || r != ' ' )
{
if (!subtrees.has(subt))
{
return true ;
}
}
}
return false ;
}
var root = newNode( 'A' );
root.left = newNode( 'B' );
root.right = newNode( 'C' );
root.left.left = newNode( 'D' );
root.left.right = newNode( 'E' );
root.right.right = newNode( 'B' );
root.right.right.right = newNode( 'E' );
root.right.right.left = newNode( 'D' );
if (dupSubUtil(root))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(n) where N is no of nodes in a binary tree
Auxiliary Space: O(n)
Last Updated :
19 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...