Open In App

Check if a Binary Tree contains duplicate subtrees of size 2 or more

Last Updated : 07 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree, the task is to check whether the Binary tree contains a duplicate sub-tree of size 2 or more
Note: Two same leaf nodes are not considered as the subtree as the size of a leaf node is one.

Example:

Input:

check-if-a-binary-tree-contains-duplicate-subtrees-of-size-2-or-more

Output: True
Explanation:

check-if-a-binary-tree-contains-duplicate-subtrees-of-size-2-or-more-2

[Naive Approach] Generating All Subtrees – O(n^2) Time and O(n) Space

The idea is to generate all subtrees (of size greater than 1) of the binary tree and store their Serialized Form in an array or hash map. Then iterate through the array/map to check for duplicate subtrees.

C++
// C++ program to find if there is a duplicate
// sub-tree of size 2 or more.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    char data;
    Node *left, *right;
    Node (char x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function which generates all the subtrees of size>2 
// and store its serialized form in map.
string dupSubRecur(Node *root, unordered_map<string, int> &map) {
    
    // For null nodes, 
    if (root == nullptr) return "N";
    
    // For leaf nodes, return its value in string.
    if (root->left==nullptr && root->right==nullptr) {
        return to_string(root->data);
    }
    
    // Process the left and right subtree.
    string left = dupSubRecur(root->left, map);
    string right = dupSubRecur(root->right, map);
    
    // Generate the serialized form.
    string curr = "";
    curr += to_string(root->data);    
    curr += '*';
    curr += left;
    curr += '*';
    curr += right;
    
    // Store the subtree in map.
    map[curr]++;
    
    return curr;
}

int dupSub(Node *root) {
    unordered_map<string,int> map;
    
    // Generate all the subtrees.
    dupSubRecur(root, map);
    
    // Check for all subtrees.
    for (auto p: map) {
        
        // If subtree is duplicate.
        if (p.second>1) {
            return 1;
        }
    }
    
    return 0;
}

int main() {
    
    //         A
    //       /   \
    //      B     C
    //     / \     \
    //    D   E     B
    //           /   \
    //          D     E
    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');

    if (dupSub(root)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to find if there is a duplicate
// sub-tree of size 2 or more.

import java.util.HashMap;

class Node {
    char data;
    Node left, right;
    
    Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    static String dupSubRecur(Node root, 
                              HashMap<String, Integer> map) {
        
        // For null nodes, 
        if (root == null) return "N";
        
        // For leaf nodes, return its value in string.
        if (root.left == null && root.right == null) {
            return String.valueOf(root.data);
        }
        
        // Process the left and right subtree.
        String left = dupSubRecur(root.left, map);
        String right = dupSubRecur(root.right, map);
        
        // Generate the serialized form.
        String curr = "";
        curr += root.data;
        curr += '*';
        curr += left;
        curr += '*';
        curr += right;
        
        // Store the subtree in map.
        map.put(curr, map.getOrDefault(curr, 0) + 1);
        
        return curr;
    }

    static int dupSub(Node root) {
        HashMap<String, Integer> map = new HashMap<>();
        
        // Generate all the subtrees.
        dupSubRecur(root, map);
        
        // Check for all subtrees.
        for (int val : map.values()) {
            
            // If subtree is duplicate.
            if (val > 1) {
                return 1;
            }
        }
        
        return 0;
    }

    public static void main(String[] args) {
        
        //         A
        //       /   \
        //      B     C
        //     / \     \
        //    D   E     B
        //           /   \
        //          D     E
        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.left = new Node('D');
        root.right.right.right = new Node('E');

        if (dupSub(root) == 1) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to find if there is a duplicate
# sub-tree of size 2 or more.

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def dupSubRecur(root, map):
    
    # For null nodes, 
    if root is None:
        return "N"
    
    # For leaf nodes, return its value in string.
    if root.left is None and root.right is None:
        return str(root.data)
    
    # Process the left and right subtree.
    left = dupSubRecur(root.left, map)
    right = dupSubRecur(root.right, map)
    
    # Generate the serialized form.
    curr = ""
    curr += str(root.data)
    curr += '*'
    curr += left
    curr += '*'
    curr += right
    
    # Store the subtree in map.
    map[curr] = map.get(curr, 0) + 1
    
    return curr

def dupSub(root):
    map = {}
    
    # Generate all the subtrees.
    dupSubRecur(root, map)
    
    # Check for all subtrees.
    for val in map.values():
        
        # If subtree is duplicate.
        if val > 1:
            return 1
    
    return 0

if __name__ == "__main__":
    
    #         A
    #       /   \
    #      B     C
    #     / \     \
    #    D   E     B
    #           /   \
    #          D     E
    root = Node('A')
    root.left = Node('B')
    root.right = Node('C')
    root.left.left = Node('D')
    root.left.right = Node('E')
    root.right.right = Node('B')
    root.right.right.left = Node('D')
    root.right.right.right = Node('E')

    if dupSub(root) == 1:
        print("True")
    else:
        print("False")
C#
// C# program to find if there is a duplicate
// sub-tree of size 2 or more.

using System;
using System.Collections.Generic;

class Node {
    public char data;
    public Node left, right;
    
    public Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    static string dupSubRecur(Node root, 
                              Dictionary<string, int> map) {
        
        // For null nodes, 
        if (root == null) return "N";
        
        // For leaf nodes, return its value in string.
        if (root.left == null && root.right == null) {
            return root.data.ToString();
        }
        
        // Process the left and right subtree.
        string left = dupSubRecur(root.left, map);
        string right = dupSubRecur(root.right, map);
        
        // Generate the serialized form.
        string curr = "";
        curr += root.data;
        curr += '*';
        curr += left;
        curr += '*';
        curr += right;
        
        // Store the subtree in map.
        if (map.ContainsKey(curr)) {
            map[curr]++;
        } else {
            map[curr] = 1;
        }
        
        return curr;
    }

    static int dupSub(Node root) {
        Dictionary<string, int> map = 
          			new Dictionary<string, int>();
        
        // Generate all the subtrees.
        dupSubRecur(root, map);
        
        // Check for all subtrees.
        foreach (int val in map.Values) {
            
            // If subtree is duplicate.
            if (val > 1) {
                return 1;
            }
        }
        
        return 0;
    }

    static void Main() {
        
        //         A
        //       /   \
        //      B     C
        //     / \     \
        //    D   E     B
        //           /   \
        //          D     E
        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.left = new Node('D');
        root.right.right.right = new Node('E');

        if (dupSub(root) == 1) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to find if there is a duplicate
// sub-tree of size 2 or more.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function dupSubRecur(root, map) {
    
    // For null nodes, 
    if (root === null) return "N";
    
    // For leaf nodes, return its value in string.
    if (root.left === null && root.right === null) {
        return root.data.toString();
    }
    
    // Process the left and right subtree.
    let left = dupSubRecur(root.left, map);
    let right = dupSubRecur(root.right, map);
    
    // Generate the serialized form.
    let curr = "";
    curr += root.data;
    curr += '*';
    curr += left;
    curr += '*';
    curr += right;
    
    // Store the subtree in map.
    map[curr] = (map[curr] || 0) + 1;
    
    return curr;
}

function dupSub(root) {
    let map = {};
    
    // Generate all the subtrees.
    dupSubRecur(root, map);
    
    // Check for all subtrees.
    for (let val of Object.values(map)) {
        
        // If subtree is duplicate.
        if (val > 1) {
            return 1;
        }
    }
    
    return 0;
}

//         A
//       /   \
//      B     C
//     / \     \
//    D   E     B
//           /   \
//          D     E
let 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.left = new Node('D');
root.right.right.right = new Node('E');

console.log(dupSub(root) === 1 ? "True" : "False");

Output
True

[Expected Approach] Using Hash Set – O(n) Time and O(n) Space

The idea is to use a hash set to store the subtrees in Serialized String Form. For a given subtree of size greater than 1, if its equivalent serialized string already exists, then return true. If all subtrees are unique, return false.

Step by step approach:

  • To identify duplicate subtrees efficiently, we only need to check subtrees of size 2 or 3, as any larger duplicate subtree would already contain smaller duplicate subtrees. This reduces the time complexity of concatenating strings to O(1) by focusing only on nodes where both children are either leaf nodes or one is a leaf and the other is null.
  • Use a hash set, say s to track unique subtree structures and an answer variable ans (initially set to false).
  • Define a function dupSubRecur that takes a node and returns a string.
    • If the node is null, return “N”.
    • If it’s a leaf node, return its value as a string.
    • For internal nodes, first process the left and right subtrees. If either subtree string is empty, return an empty string. Otherwise, concatenate the current node with its left and right subtree strings. If this concatenated string is in the hash set, set ans to true; if not, insert it.
  • Return an empty string for each processed subtree, as upper subtrees don’t need further processing.
C++
// C++ program to find if there is a duplicate
// sub-tree of size 2 or more.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    char data;
    Node *left, *right;
    Node (char x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function which checks all the subtree of size 2 or 
// 3 if they are duplicate.
string dupSubRecur(Node *root, unordered_set<string> &s, 
                   int &ans) {
    
    // For null nodes, 
    if (root == nullptr) return "N";
    
    // For leaf nodes, return its value in string.
    if (root->left==nullptr && root->right==nullptr) {
        return to_string(root->data);
    }
    
    string curr = "";
    curr += to_string(root->data);
    
    // Process the left and right subtree.
    string left = dupSubRecur(root->left, s, ans);
    string right = dupSubRecur(root->right, s, ans);
    
    // If the node is parent to 2 
    // leaf nodes, or 1 leaf node and 1 
    // null node, then concatenate the strings
    if (left != "" && right != "") {
        curr += '*';
        curr += left;
        curr += '*';
        curr += right;
    }
    
    // Otherwise, there is no need 
    // to process this node.
    else {
        return "";
    }
    
    // If this subtree string is already 
    // present in set, set ans to 1.
    if (s.find(curr) != s.end()) {
        ans = 1;
    }
    
    // Else add this string to set.
    else {
        s.insert(curr);
    }
    
    return "";
}

int dupSub(Node *root) {
    int ans = 0;
    unordered_set<string> s;
    
    dupSubRecur(root, s, ans);
    
    return ans;
}

int main() {
    
    //         A
    //       /   \
    //      B     C
    //     / \     \
    //    D   E     B
    //           /   \
    //          D     E
    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');

    if (dupSub(root)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    return 0;
}
Java
// Java program to find if there is a duplicate
// sub-tree of size 2 or more.

import java.util.HashSet;

class Node {
    char data;
    Node left, right;

    Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function which checks all the subtree of size 2 or 
    // 3 if they are duplicate.
    static String dupSubRecur(Node root, HashSet<String> s,
                              int[] ans) {
        
        // For null nodes,
        if (root == null) return "N";
        
        // For leaf nodes, return its value in string.
        if (root.left == null && root.right == null) {
            return String.valueOf(root.data);
        }
        
        String curr = "";
        curr += root.data;
        
        // Process the left and right subtree.
        String left = dupSubRecur(root.left, s, ans);
        String right = dupSubRecur(root.right, s, ans);
        
        // If the node is parent to 2 
        // leaf nodes, or 1 leaf node and 1 
        // null node, then concatenate the strings
        if (!left.equals("") && !right.equals("")) {
            curr += '*' + left + '*' + right;
        } else {
            return "";
        }
        
        // If this subtree string is already 
        // present in set, set ans to 1.
        if (s.contains(curr)) {
            ans[0] = 1;
        } else {
            s.add(curr);
        }
        
        return "";
    }

    static int dupSub(Node root) {
        int[] ans = {0};
        HashSet<String> s = new HashSet<>();
        
        dupSubRecur(root, s, ans);
        
        return ans[0];
    }

    public static void main(String[] args) {
        
        //         A
        //       /   \
        //      B     C
        //     / \     \
        //    D   E     B
        //           /   \
        //          D     E
        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');

        if (dupSub(root) == 1) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to find if there is a duplicate
# sub-tree of size 2 or more.

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Function which checks all the subtree of size 2 or 
# 3 if they are duplicate.
def dupSubRecur(root, s, ans):
    
    # For null nodes,
    if root is None:
        return "N"
    
    # For leaf nodes, return its value in string.
    if root.left is None and root.right is None:
        return str(root.data)
    
    curr = str(root.data)
    
    # Process the left and right subtree.
    left = dupSubRecur(root.left, s, ans)
    right = dupSubRecur(root.right, s, ans)
    
    # If the node is parent to 2 
    # leaf nodes, or 1 leaf node and 1 
    # null node, then concatenate the strings
    if left != "" and right != "":
        curr += '*' + left + '*' + right
    else:
        return ""
    
    # If this subtree string is already 
    # present in set, set ans to 1.
    if curr in s:
        ans[0] = 1
    else:
        s.add(curr)
    
    return ""

def dupSub(root):
    ans = [0]
    s = set()
    
    dupSubRecur(root, s, ans)
    
    return ans[0]

if __name__ == "__main__":
    
    #         A
    #       /   \
    #      B     C
    #     / \     \
    #    D   E     B
    #           /   \
    #          D     E
    root = Node('A')
    root.left = Node('B')
    root.right = Node('C')
    root.left.left = Node('D')
    root.left.right = Node('E')
    root.right.right = Node('B')
    root.right.right.right = Node('E')
    root.right.right.left = Node('D')

    if dupSub(root):
        print("True")
    else:
        print("False")
C#
// C# program to find if there is a duplicate
// sub-tree of size 2 or more.

using System;
using System.Collections.Generic;

class Node {
    public char data;
    public Node left, right;

    public Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function which checks all the subtree of size 2 or 
    // 3 if they are duplicate.
    static string dupSubRecur(Node root, HashSet<string> s, 
                              ref int ans) {
        
        // For null nodes,
        if (root == null) return "N";
        
        // For leaf nodes, return its value in string.
        if (root.left == null && root.right == null) {
            return root.data.ToString();
        }
        
        string curr = root.data.ToString();
        
        // Process the left and right subtree.
        string left = dupSubRecur(root.left, s, ref ans);
        string right = dupSubRecur(root.right, s, ref ans);
        
        // If the node is parent to 2 
        // leaf nodes, or 1 leaf node and 1 
        // null node, then concatenate the strings
        if (left != "" && right != "") {
            curr += "*" + left + "*" + right;
        } else {
            return "";
        }
        
        // If this subtree string is already 
        // present in set, set ans to 1.
        if (s.Contains(curr)) {
            ans = 1;
        } else {
            s.Add(curr);
        }
        
        return "";
    }

    static int dupSub(Node root) {
        int ans = 0;
        HashSet<string> s = new HashSet<string>();
        
        dupSubRecur(root, s, ref ans);
        
        return ans;
    }

    static void Main() {
        
        //         A
        //       /   \
        //      B     C
        //     / \     \
        //    D   E     B
        //           /   \
        //          D     E
        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');

        Console.WriteLine(dupSub(root) == 1 ? "True" : "False");
    }
}
JavaScript
// JavaScript program to find if there is a duplicate
// sub-tree of size 2 or more.

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Function which checks all the subtree of size 2 or 
// 3 if they are duplicate.
function dupSubRecur(root, s, ans) {
    
    // For null nodes,
    if (root === null) return "N";
    
    // For leaf nodes, return its value in string.
    if (root.left === null && root.right === null) {
        return root.data.toString();
    }
    
    let curr = root.data.toString();
    
    // Process the left and right subtree.
    let left = dupSubRecur(root.left, s, ans);
    let right = dupSubRecur(root.right, s, ans);
    
    // If the node is parent to 2 
    // leaf nodes, or 1 leaf node and 1 
    // null node, then concatenate the strings
    if (left !== "" && right !== "") {
        curr += '*' + left + '*' + right;
    } else {
        return "";
    }
    
    // If this subtree string is already 
    // present in set, set ans to 1.
    if (s.has(curr)) {
        ans[0] = 1;
    } else {
        s.add(curr);
    }
    
    return "";
}

function dupSub(root) {
    let ans = [0];
    let s = new Set();
    
    dupSubRecur(root, s, ans);
    
    return ans[0];
}

//         A
//       /   \
//      B     C
//     / \     \
//    D   E     B
//           /   \
//          D     E
let 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');

console.log(dupSub(root) ? "True" : "False");

Output
True


Next Article
Article Tags :
Practice Tags :

Similar Reads