Open In App

Check if a Binary tree is Subtree of another Binary tree | Set 3

Last Updated : 09 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T(root1) is a tree S(root2) consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree and the subtree corresponding to any other node is called a proper subtree.

Examples:       

Input:  

Check-if-a-Binary-Tree-is-subtree-of-another-binary-tree

Output: True

Approach:

The approach is to find all nodes at the same height as the height of S(root2) in T(root1) and then compare. First, we will calculate the height of the subtree to be checked. Next, we will traverse the main tree to find nodes that match the height of the subtree. For each matching node, we will check if the subtree structure and values are identical.

Step-By-Step Implementation :

  • Initially calculate the height of the given subtree S(root2).
  • In the next step, find all the nodes from T(root1) which are having height as the height of the S(root2), and store their address.
  • Then from every node we stored, we check if that is an identical subtree or not.
  • In this approach, there is no need to check for all the nodes whether it is an identical subtree or not as we have height as a parameter at which actually identical subtree validation must be performed.

Below is the implementation of the above.

C++
// C++ Program to check if a binary tree is subtree
// of another binary tree

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int val) {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Function to calculate the height of the tree
int heightOfTree(Node* root) {
    if (!root)
        return 0;

    // Calculate the left subtree and right subtree height
    int left = heightOfTree(root->left);
    int right = heightOfTree(root->right);
    return 1 + max(left, right);
}

// Function to check if it is a subtree or not
bool checkSubTree(Node* root1, Node* root2) {
    if (root1 == nullptr && root2 == nullptr)
        return true;

    if (root1 == nullptr || root2 == nullptr)
        return false;

    if (root1->data != root2->data)
        return false;

    return checkSubTree(root1->left, root2->left)
        && checkSubTree(root1->right, root2->right);
}

// Function to extract the nodes of height of the subtree i.e tree-S
// from the parent tree(T-tree) using the height of the tree
int subtreeHeight(Node* root, vector<Node*>& nodes, int h) {
    if (root == nullptr)
        return 0;

    else {
        
        // Calculating the height of the tree at each node
        int left = subtreeHeight(root->left, nodes, h);
        int right = subtreeHeight(root->right, nodes, h);
        int height = max(left, right) + 1;

        // If height equals to height of the subtree
        // then store it
        if (height == h)
            nodes.push_back(root);

        return height;
    }
}

// Function to check if it is a subtree
bool isSubTree(Node* root1, Node* root2) {
    if (root1 == nullptr && root2 == nullptr)
        return true;

    if (root1 == nullptr || root2 == nullptr)
        return false;

    // Calculate the height of subtree-S
    int h = heightOfTree(root2);
    vector<Node*> nodes;

    // Extract all the nodes of height of subtree(S) i.e height-h
    int h1 = subtreeHeight(root1, nodes, h);

    bool result = false;
    int n = nodes.size();

    for (int i = 0; i < n; i++) {
      
        // Check if it is a subtree of the parent tree or not
        if (nodes[i]->data == root2->data)
            result = checkSubTree(nodes[i], root2);

        if (result)
            return true;
    }
    return false;
}

int main() {
    
    // Tree root1:
    //       1
    //      / \
    //     2   3
    //    / \  / 
    //   4   5 6


    Node* root1 = new Node(1);
    root1->left = new Node(2);
    root1->right = new Node(3);
    root1->left->left = new Node(4);
    root1->left->right = new Node(5);
    root1->right->left = new Node(6);
    
    // Tree root2:
    //     3
    //    / 
    //   6
    Node* root2 = new Node(3);
    root2->left = new Node(6);
    
    if (isSubTree(root1, root2))
        cout << "true" << endl;
    else
        cout << "false" << endl;

    return 0;
}
Java
// Java Program to check if a binary tree is subtree
// of another binary tree

import java.util.ArrayList;

class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
  
    // Function to calculate the height of the tree
    static int heightOfTree(Node root) {
        if (root == null)
            return 0;

        // Calculate the left subtree and right subtree height
        int left = heightOfTree(root.left);
        int right = heightOfTree(root.right);
        return 1 + Math.max(left, right);
    }

    // Function to check if it is a subtree or not
    static boolean checkSubTree(Node root1, Node root2) {
        if (root1 == null && root2 == null)
            return true;

        if (root1 == null || root2 == null)
            return false;

        if (root1.data != root2.data)
            return false;

        return checkSubTree(root1.left, root2.left) 
        && checkSubTree(root1.right, root2.right);
    }

    // Function to extract the nodes of height of the subtree i.e tree-S
    // from the parent tree(T-tree) using the height of the tree
    static int subtreeHeight(Node root, ArrayList<Node> nodes, int h) {
        if (root == null)
            return 0;

        // Calculating the height of the tree at each node
        int left = subtreeHeight(root.left, nodes, h);
        int right = subtreeHeight(root.right, nodes, h);
        int height = Math.max(left, right) + 1;

        // If height equals to height of the subtree
        // then store it
        if (height == h)
            nodes.add(root);

        return height;
    }

    // Function to check if it is a subtree
    static boolean isSubTree(Node root1, Node root2) {
        if (root1 == null && root2 == null)
            return true;

        if (root1 == null || root2 == null)
            return false;

        // Calculate the height of subtree-S
        int h = heightOfTree(root2);
        ArrayList<Node> nodes = new ArrayList<>();

        // Extract all the nodes of height of
        // subtree(S) i.e height-h
        int h1 = subtreeHeight(root1, nodes, h);

        boolean result = false;
        int n = nodes.size();

        for (int i = 0; i < n; i++) {
          
            // Check if it is a subtree of the parent tree or not
            if (nodes.get(i).data == root2.data)
                result = checkSubTree(nodes.get(i), root2);

            if (result)
                return true;
        }
        return false;
    }

    public static void main(String[] args) {
        
        // Tree root1:
        //       1
        //      / \
        //     2   3
        //    / \  / 
        //   4   5 6
        //

        Node root1 = new Node(1);
        root1.left = new Node(2);
        root1.right = new Node(3);
        root1.left.left = new Node(4);
        root1.left.right = new Node(5);
        root1.right.left = new Node(6);
        
        // Tree root2:
        //     3
        //    / 
        //   6

        Node root2 = new Node(3);
        root2.left = new Node(6);
        
        if (isSubTree(root1, root2))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# Python Program to check if a binary tree is subtree 
# of another binary tree

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

# Function to calculate the height of the tree
def heightOfTree(root):
    if not root:
        return 0

    # Calculate the left subtree and right subtree height
    left = heightOfTree(root.left)
    right = heightOfTree(root.right)
    return 1 + max(left, right)

# Function to check if it is a subtree or not
def checkSubTree(root1, root2):
    if root1 is None and root2 is None:
        return True

    if root1 is None or root2 is None:
        return False

    if root1.data != root2.data:
        return False

    return checkSubTree(root1.left, root2.left) \
    and checkSubTree(root1.right, root2.right)

# Function to extract the nodes of height of the subtree i.e tree-S
# from the parent tree(T-tree) using the height of the tree
def subtreeHeight(root, nodes, h):
    if root is None:
        return 0

    left = subtreeHeight(root.left, nodes, h)
    right = subtreeHeight(root.right, nodes, h)
    height = max(left, right) + 1

    # If height equals to height of the subtree
    # then store it
    if height == h:
        nodes.append(root)

    return height

# Function to check if it is a subtree
def isSubTree(root1, root2):
    if root1 is None and root2 is None:
        return True

    if root1 is None or root2 is None:
        return False

    # Calculate the height of subtree-S
    h = heightOfTree(root2)
    nodes = []

    # Extract all the nodes of height of 
    # subtree(S) i.e height-h
    h1 = subtreeHeight(root1, nodes, h)

    result = False
    n = len(nodes)

    for i in range(n):

        # Check if it is a subtree of the parent
        # tree or not
        if nodes[i].data == root2.data:
            result = checkSubTree(nodes[i], root2)

        if result:
            return True
    return False


# Tree root1:
#       1
#      / \
#     2   3
#    / \  / 
#   4   5 6

root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root1.right.left = Node(6)

# Tree root2:
#     3
#    / 
#   6

root2 = Node(3)
root2.left = Node(6)

if isSubTree(root1, root2):
    print("true")
else:
    print("false")
C#
// C# Program to check if a binary tree is subtree 
// of another binary tree

using System;
using System.Collections.Generic;

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

    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

class GfG {
  
    // Function to calculate the height of the tree
    static int HeightOfTree(Node root) {
        if (root == null)
            return 0;

        // Calculate the left subtree and right
        // subtree height
        int left = HeightOfTree(root.left);
        int right = HeightOfTree(root.right);
        return 1 + Math.Max(left, right);
    }

    // Function to check if it is a subtree or not
    static bool CheckSubTree(Node root1, Node root2) {
        if (root1 == null && root2 == null)
            return true;

        if (root1 == null || root2 == null)
            return false;

        if (root1.data != root2.data)
            return false;

        return CheckSubTree(root1.left, root2.left) 
        && CheckSubTree(root1.right, root2.right);
    }

    // Function to extract the nodes of height of the subtree i.e tree-S
    // from the parent tree(T-tree) using the height of the tree
    static int SubtreeHeight(Node root, List<Node> nodes, int h) {
        if (root == null)
            return 0;

        // Calculating the height of the tree at each node
        int left = SubtreeHeight(root.left, nodes, h);
        int right = SubtreeHeight(root.right, nodes, h);
        int height = Math.Max(left, right) + 1;

        // If height equals to height of the subtree
        // then store it
        if (height == h)
            nodes.Add(root);

        return height;
    }

    // Function to check if it is a subtree
    static bool IsSubTree(Node root1, Node root2) {
        if (root1 == null && root2 == null)
            return true;

        if (root1 == null || root2 == null)
            return false;

        // Calculate the height of subtree-S
        int h = HeightOfTree(root2);
        List<Node> nodes = new List<Node>();

        // Extract all the nodes of height of 
        // subtree(S) i.e height-h
        SubtreeHeight(root1, nodes, h);

        bool result = false;
        int n = nodes.Count;

        for (int i = 0; i < n; i++) {
            
            // Check if it is a subtree of the parent tree or not
            if (nodes[i].data == root2.data)
                result = CheckSubTree(nodes[i], root2);

            if (result)
                return true;
        }
        return false;
    }

    static void Main(string[] args) {

        // Tree root1:
        //       1
        //      / \
        //     2   3
        //    / \  / 
        //   4   5 6
        //
        

        Node root1 = new Node(1);
        root1.left = new Node(2);
        root1.right = new Node(3);
        root1.left.left = new Node(4);
        root1.left.right = new Node(5);
        root1.right.left = new Node(6);
        
        // Tree root2:
        //     3
        //    / 
        //   6
        Node root2 = new Node(3);
        root2.left = new Node(6);

        if (IsSubTree(root1, root2))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// JavaScript Program to check if a binary tree is subtree 
// of another binary tree

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

// Function to calculate the height 
// of the tree
function heightOfTree(root) {
    if (!root) return 0;

    // Calculate the left subtree and right
    // subtree height
    const left = heightOfTree(root.left);
    const right = heightOfTree(root.right);
    return 1 + Math.max(left, right);
}

// Function to check if it is a subtree or not
function checkSubTree(root1, root2) {
    if (root1 === null && root2 === null) return true;

    if (root1 === null || root2 === null) return false;

    if (root1.data !== root2.data) return false;

    return checkSubTree(root1.left, root2.left)
    && checkSubTree(root1.right, root2.right);
}

// Function to extract the nodes of height of the subtree i.e tree-S
// from the parent tree(T-tree) using the height of the tree
function subtreeHeight(root, nodes, h) {
    if (root === null) return 0;

    const left = subtreeHeight(root.left, nodes, h);
    const right = subtreeHeight(root.right, nodes, h);
    const height = Math.max(left, right) + 1;

    // If height equals to height of the subtree 
    // then store it
    if (height === h) nodes.push(root);

    return height;
}

// Function to check if it is a subtree
function isSubTree(root1, root2) {
    if (root1 === null && root2 === null) return true;

    if (root1 === null || root2 === null) return false;

    // Calculate the height of subtree-S
    const h = heightOfTree(root2);
    const nodes = [];

    // Extract all the nodes of height of 
    // subtree(S) i.e height-h
    const h1 = subtreeHeight(root1, nodes, h);

    let result = false;
    const n = nodes.length;

    for (let i = 0; i < n; i++) {
    
        // Check if it is a subtree of the 
        // parent tree or not
        if (nodes[i].data === root2.data) {
            result = checkSubTree(nodes[i], root2);
        }

        if (result) return true;
    }
    return false;
}

// Tree root1:
//       1
//      / \
//     2   3
//    / \  / 
//   4   5 6

const root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.left = new Node(6);

// Tree root2:
//     3
//    / 
//   6

const root2 = new Node(3);
root2.left = new Node(6);

if (isSubTree(root1, root2)) {
    console.log("true");
} else {
    console.log("false");
}

Output
true

 Time Complexity: O(n) where n is the number of nodes in Binary Tree.
Auxiliary Space: O( 2h ) where h is the height of Binary Tree.


Next Article
Article Tags :
Practice Tags :

Similar Reads