# Check if a binary tree is subtree of another binary tree | Set 1

• Difficulty Level : Medium
• Last Updated : 17 Jun, 2022

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

```        Tree 2
10
/    \
4       6
\
30```
```        Tree 1
26
/   \
10     3
/    \     \
4       6      3
\
30```
Recommended Practice

Solution: Traverse the tree T in preorder fashion. For every visited node in the traversal, see if the subtree rooted with this node is identical to S.
Following is the implementation for this.

## C++

 `// C++ program to check if binary tree` `// is subtree of another binary tree` `#include` `using` `namespace` `std;`   `/* A binary tree node has data, ` `left child and right child */` `class` `node ` `{ ` `    ``public``:` `    ``int` `data; ` `    ``node* left; ` `    ``node* right; ` `}; `   `/* A utility function to check ` `whether trees with roots as root1 and ` `root2 are identical or not */` `bool` `areIdentical(node * root1, node *root2) ` `{ ` `    ``/* base cases */` `    ``if` `(root1 == NULL && root2 == NULL) ` `        ``return` `true``; `   `    ``if` `(root1 == NULL || root2 == NULL) ` `        ``return` `false``; `   `    ``/* Check if the data of both roots is ` `    ``same and data of left and right ` `    ``subtrees are also same */` `    ``return` `(root1->data == root2->data && ` `            ``areIdentical(root1->left, root2->left) && ` `            ``areIdentical(root1->right, root2->right) ); ` `} `     `/* This function returns true if S ` `is a subtree of T, otherwise false */` `bool` `isSubtree(node *T, node *S) ` `{ ` `    ``/* base cases */` `    ``if` `(S == NULL) ` `        ``return` `true``; `   `    ``if` `(T == NULL) ` `        ``return` `false``; `   `    ``/* Check the tree with root as current node */` `    ``if` `(areIdentical(T, S)) ` `        ``return` `true``; `   `    ``/* If the tree with root as current ` `    ``node doesn't match then try left ` `    ``and right subtrees one by one */` `    ``return` `isSubtree(T->left, S) || ` `        ``isSubtree(T->right, S); ` `} `     `/* Helper function that allocates ` `a new node with the given data ` `and NULL left and right pointers. */` `node* newNode(``int` `data) ` `{ ` `    ``node* Node = ``new` `node(); ` `    ``Node->data = data; ` `    ``Node->left = NULL; ` `    ``Node->right = NULL; ` `    ``return``(Node); ` `} `   `/* Driver code*/` `int` `main() ` `{ ` `    ``// TREE 1 ` `    ``/* Construct the following tree ` `            ``26 ` `            ``/ \ ` `        ``10 3 ` `        ``/ \ \ ` `    ``4 6 3 ` `    ``\ ` `        ``30 ` `    ``*/` `    ``node *T = newNode(26); ` `    ``T->right         = newNode(3); ` `    ``T->right->right = newNode(3); ` `    ``T->left         = newNode(10); ` `    ``T->left->left     = newNode(4); ` `    ``T->left->left->right = newNode(30); ` `    ``T->left->right     = newNode(6); `   `    ``// TREE 2 ` `    ``/* Construct the following tree ` `        ``10 ` `        ``/ \ ` `    ``4 6 ` `    ``\ ` `        ``30 ` `    ``*/` `    ``node *S = newNode(10); ` `    ``S->right     = newNode(6); ` `    ``S->left     = newNode(4); ` `    ``S->left->right = newNode(30); `     `    ``if` `(isSubtree(T, S)) ` `        ``cout << ``"Tree 2 is subtree of Tree 1"``; ` `    ``else` `        ``cout << ``"Tree 2 is not a subtree of Tree 1"``; `   `    ``return` `0; ` `} `   `// This code is contributed by rathbhupendra`

## C

 `#include ` `#include `   `/* A binary tree node has data, left child and right child */` `struct` `node` `{` `    ``int` `data;` `    ``struct` `node* left;` `    ``struct` `node* right;` `};`   `/* A utility function to check whether trees with roots as root1 and` `   ``root2 are identical or not */` `bool` `areIdentical(``struct` `node * root1, ``struct` `node *root2)` `{` `    ``/* base cases */` `    ``if` `(root1 == NULL && root2 == NULL)` `        ``return` `true``;`   `    ``if` `(root1 == NULL || root2 == NULL)` `        ``return` `false``;`   `    ``/* Check if the data of both roots is same and data of left and right` `       ``subtrees are also same */` `    ``return` `(root1->data == root2->data   &&` `            ``areIdentical(root1->left, root2->left) &&` `            ``areIdentical(root1->right, root2->right) );` `}`     `/* This function returns true if S is a subtree of T, otherwise false */` `bool` `isSubtree(``struct` `node *T, ``struct` `node *S)` `{` `    ``/* base cases */` `    ``if` `(S == NULL)` `        ``return` `true``;`   `    ``if` `(T == NULL)` `        ``return` `false``;`   `    ``/* Check the tree with root as current node */` `    ``if` `(areIdentical(T, S))` `        ``return` `true``;`   `    ``/* If the tree with root as current node doesn't match then` `       ``try left and right subtrees one by one */` `    ``return` `isSubtree(T->left, S) ||` `           ``isSubtree(T->right, S);` `}`     `/* Helper function that allocates a new node with the given data` `   ``and NULL left and right pointers. */` `struct` `node* newNode(``int` `data)` `{` `    ``struct` `node* node =` `        ``(``struct` `node*)``malloc``(``sizeof``(``struct` `node));` `    ``node->data  = data;` `    ``node->left  = NULL;` `    ``node->right = NULL;` `    ``return``(node);` `}`   `/* Driver program to test above function */` `int` `main()` `{` `    ``// TREE 1` `    ``/* Construct the following tree` `              ``26` `            ``/   \` `          ``10     3` `        ``/    \     \` `      ``4      6      3` `       ``\` `        ``30` `    ``*/` `    ``struct` `node *T        = newNode(26);` `    ``T->right              = newNode(3);` `    ``T->right->right       = newNode(3);` `    ``T->left               = newNode(10);` `    ``T->left->left         = newNode(4);` `    ``T->left->left->right  = newNode(30);` `    ``T->left->right        = newNode(6);`   `    ``// TREE 2` `    ``/* Construct the following tree` `          ``10` `        ``/    \` `      ``4      6` `       ``\` `        ``30` `    ``*/` `    ``struct` `node *S    = newNode(10);` `    ``S->right          = newNode(6);` `    ``S->left           = newNode(4);` `    ``S->left->right    = newNode(30);`     `    ``if` `(isSubtree(T, S))` `        ``printf``(``"Tree 2 is subtree of Tree 1"``);` `    ``else` `        ``printf``(``"Tree 2 is not a subtree of Tree 1"``);`   `    ``getchar``();` `    ``return` `0;` `}`

## Java

 `// Java program to check if binary tree is subtree of another binary tree` ` `  `// A binary tree node` `class` `Node ` `{` `    ``int` `data;` `    ``Node left, right, nextRight;` ` `  `    ``Node(``int` `item) ` `    ``{` `        ``data = item;` `        ``left = right = nextRight = ``null``;` `    ``}` `}` ` `  `class` `BinaryTree ` `{` `    ``Node root1,root2;` ` `  `    ``/* A utility function to check whether trees with roots as root1 and` `       ``root2 are identical or not */` `    ``boolean` `areIdentical(Node root1, Node root2) ` `    ``{` ` `  `        ``/* base cases */` `        ``if` `(root1 == ``null` `&& root2 == ``null``)` `            ``return` `true``;` ` `  `        ``if` `(root1 == ``null` `|| root2 == ``null``)` `            ``return` `false``;` ` `  `        ``/* Check if the data of both roots is same and data of left and right` `           ``subtrees are also same */` `        ``return` `(root1.data == root2.data` `                ``&& areIdentical(root1.left, root2.left)` `                ``&& areIdentical(root1.right, root2.right));` `    ``}` ` `  `    ``/* This function returns true if S is a subtree of T, otherwise false */` `    ``boolean` `isSubtree(Node T, Node S) ` `    ``{` `        ``/* base cases */` `        ``if` `(S == ``null``) ` `            ``return` `true``;` ` `  `        ``if` `(T == ``null``)` `            ``return` `false``;` ` `  `        ``/* Check the tree with root as current node */` `        ``if` `(areIdentical(T, S)) ` `            ``return` `true``;` ` `  `        ``/* If the tree with root as current node doesn't match then` `           ``try left and right subtrees one by one */` `        ``return` `isSubtree(T.left, S)` `                ``|| isSubtree(T.right, S);` `    ``}` ` `  `    ``public` `static` `void` `main(String args[]) ` `    ``{` `        ``BinaryTree tree = ``new` `BinaryTree();` `         `  `        ``// TREE 1` `        ``/* Construct the following tree` `              ``26` `             ``/   \` `            ``10     3` `           ``/    \     \` `          ``4      6      3` `           ``\` `            ``30  */` `          `  `        ``tree.root1 = ``new` `Node(``26``);` `        ``tree.root1.right = ``new` `Node(``3``);` `        ``tree.root1.right.right = ``new` `Node(``3``);` `        ``tree.root1.left = ``new` `Node(``10``);` `        ``tree.root1.left.left = ``new` `Node(``4``);` `        ``tree.root1.left.left.right = ``new` `Node(``30``);` `        ``tree.root1.left.right = ``new` `Node(``6``);` ` `  `        ``// TREE 2` `        ``/* Construct the following tree` `           ``10` `         ``/    \` `         ``4      6` `          ``\` `          ``30  */` `          `  `        ``tree.root2 = ``new` `Node(``10``);` `        ``tree.root2.right = ``new` `Node(``6``);` `        ``tree.root2.left = ``new` `Node(``4``);` `        ``tree.root2.left.right = ``new` `Node(``30``);` ` `  `        ``if` `(tree.isSubtree(tree.root1, tree.root2))` `            ``System.out.println(``"Tree 2 is subtree of Tree 1 "``);` `        ``else` `            ``System.out.println(``"Tree 2 is not a subtree of Tree 1"``);` `    ``}` `}` ` `  `// This code has been contributed by Mayank Jaiswal`

## Python3

 `# Python program to check binary tree is a subtree of ` `# another tree`   `# A binary tree node` `class` `Node:`   `    ``# Constructor to create a new node` `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data ` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# A utility function to check whether trees with roots` `# as root 1 and root2 are indetical or not` `def` `areIdentical(root1, root2):` `    `  `    ``# Base Case` `    ``if` `root1 ``is` `None` `and` `root2 ``is` `None``:` `        ``return` `True` `    ``if` `root1 ``is` `None` `or` `root2 ``is` `None``:` `        ``return` `False`   `    ``# Check fi the data of both roots is same and data of` `    ``# left and right subtrees are also same` `    ``return` `(root1.data ``=``=` `root2.data ``and` `            ``areIdentical(root1.left , root2.left)``and` `            ``areIdentical(root1.right, root2.right)` `            ``) `   `# This function returns True if S is a subtree of T,` `# otherwise False` `def` `isSubtree(T, S):` `    `  `    ``# Base Case` `    ``if` `S ``is` `None``:` `        ``return` `True`   `    ``if` `T ``is` `None``:` `        ``return` `False`   `    ``# Check the tree with root as current node` `    ``if` `(areIdentical(T, S)):` `        ``return` `True`   `    ``# IF the tree with root as current node doesn't match` `    ``# then try left and right subtree one by one` `    ``return` `isSubtree(T.left, S) ``or` `isSubtree(T.right, S)`     `# Driver program to test above function`   `""" TREE 1` `     ``Construct the following tree` `              ``26` `            ``/   \` `          ``10     3` `        ``/    \     \` `      ``4      6      3` `       ``\` `        ``30` `    ``"""`   `T ``=` `Node(``26``)` `T.right ``=` `Node(``3``)` `T.right.right  ``=` `Node(``3``)` `T.left ``=` `Node(``10``)` `T.left.left ``=` `Node(``4``)` `T.left.left.right ``=` `Node(``30``)` `T.left.right ``=` `Node(``6``)`   `""" TREE 2` `     ``Construct the following tree` `          ``10` `        ``/    \` `      ``4      6` `       ``\` `        ``30` `    ``"""` `S ``=` `Node(``10``)` `S.right ``=` `Node(``6``)` `S.left ``=` `Node(``4``)` `S.left.right ``=` `Node(``30``)`   `if` `isSubtree(T, S):` `    ``print` `(``"Tree 2 is subtree of Tree 1"``)` `else` `:` `    ``print` `(``"Tree 2 is not a subtree of Tree 1"``)`   `# This code is contributed by Nikhil Kumar Singh(nickzuck_007)`

## C#

 `// C# program to check if binary tree ` `// is subtree of another binary tree ` `using` `System;`   `// A binary tree node ` `class` `Node ` `{ ` `    ``public` `int` `data; ` `    ``public` `Node left, right, nextRight; `   `    ``public` `Node(``int` `item) ` `    ``{ ` `        ``data = item; ` `        ``left = right = nextRight = ``null``; ` `    ``} ` `} `   `public` `class` `BinaryTree ` `{ ` `    ``Node root1,root2; `   `    ``/* A utility function to check whether` `        ``trees with roots as root1 and ` `        ``root2 are identical or not */` `    ``bool` `areIdentical(Node root1, Node root2) ` `    ``{ `   `        ``/* base cases */` `        ``if` `(root1 == ``null` `&& root2 == ``null``) ` `            ``return` `true``; `   `        ``if` `(root1 == ``null` `|| root2 == ``null``) ` `            ``return` `false``; `   `        ``/* Check if the data of both roots is` `        ``same and data of left and right ` `        ``subtrees are also same */` `        ``return` `(root1.data == root2.data ` `                ``&& areIdentical(root1.left, root2.left) ` `                ``&& areIdentical(root1.right, root2.right)); ` `    ``} `   `    ``/* This function returns true if S is ` `    ``a subtree of T, otherwise false */` `    ``bool` `isSubtree(Node T, Node S) ` `    ``{ ` `        ``/* base cases */` `        ``if` `(S == ``null``) ` `            ``return` `true``; `   `        ``if` `(T == ``null``) ` `            ``return` `false``; `   `        ``/* Check the tree with root as current node */` `        ``if` `(areIdentical(T, S)) ` `            ``return` `true``; `   `        ``/* If the tree with root as current ` `          ``node doesn't match then try left` `          ``and right subtrees one by one */` `        ``return` `isSubtree(T.left, S) ` `                ``|| isSubtree(T.right, S); ` `    ``} `   `    ``// Driver code` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``BinaryTree tree = ``new` `BinaryTree(); ` `        `  `        ``// TREE 1 ` `        ``/* Construct the following tree ` `            ``26 ` `            ``/ \ ` `            ``10 3 ` `        ``/ \ \ ` `        ``4 6 3 ` `        ``\ ` `            ``30 */` `            `  `        ``tree.root1 = ``new` `Node(26); ` `        ``tree.root1.right = ``new` `Node(3); ` `        ``tree.root1.right.right = ``new` `Node(3); ` `        ``tree.root1.left = ``new` `Node(10); ` `        ``tree.root1.left.left = ``new` `Node(4); ` `        ``tree.root1.left.left.right = ``new` `Node(30); ` `        ``tree.root1.left.right = ``new` `Node(6); `   `        ``// TREE 2 ` `        ``/* Construct the following tree ` `        ``10 ` `        ``/ \ ` `        ``4 6 ` `        ``\ ` `        ``30 */` `            `  `        ``tree.root2 = ``new` `Node(10); ` `        ``tree.root2.right = ``new` `Node(6); ` `        ``tree.root2.left = ``new` `Node(4); ` `        ``tree.root2.left.right = ``new` `Node(30); `   `        ``if` `(tree.isSubtree(tree.root1, tree.root2)) ` `            ``Console.WriteLine(``"Tree 2 is subtree of Tree 1 "``); ` `        ``else` `            ``Console.WriteLine(``"Tree 2 is not a subtree of Tree 1"``); ` `    ``} ` `} `   `/* This code is contributed by Rajput-Ji*/`

## Javascript

 ``

Output:

`Tree 2 is subtree of Tree 1 `

Time Complexity: Time worst-case complexity of above solution is O(mn) where m and n are number of nodes in given two trees.

Auxiliary space: O(n)

We can solve the above problem in O(n) time. Please refer Check if a binary tree is subtree of another binary tree | Set 2 for O(n) solution.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :