Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Last Updated :
12 Jul, 2025
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T.
For Example:
Input:
Tree T -
1
/ \
2 3
/ \ / \
4 5 6 7
Tree S -
2
/ \
4 5
Output: YES
Explanation:
The above tree is the subtree of the tree T,
Hence the output is YES
Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each node of the tree that Pre-order traversal of that tree is the same as the Pre-order Traversal of the tree S with taking care of Null values that is by including the Null values in the Traversal list, because if the null values are not taken care then two different trees can have same pre-order traversal. Such as in the case of below trees -
1 1
/ \ / \
2 N N 2
/ \ / \
N N N N
Pre-order Traversal of both the trees will be -
{1, 2} - In case of without taking care of null values
{1, 2, N, N, N} and {1, N, 2, N, N}
In case of taking care of null values.
Algorithm:
- Declare a stack, to keep track of the left and right child of the nodes.
- Push the root node of the tree T.
- Run a loop while the stack is not empty and then check that if the pre-order traversal of the top node of the stack is the same, then return true.
- If the pre-order traversal does not match with the tree then pop the top node from the stack and push its left and right child of the popped node.
Below is the implementation of the above approach:
C++
// C++ implementation to check
// if a tree is a subtree of
// another binary tree
#include <bits/stdc++.h>
using namespace std;
// Structure of the
// binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create
// new node
Node* newNode(int x)
{
Node* temp = (Node*)malloc(
sizeof(Node));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Function to check if two trees
// have same pre-order traversal
bool areTreeIdentical(Node* t1, Node* t2)
{
stack<Node*> s1;
stack<Node*> s2;
Node* temp1;
Node* temp2;
s1.push(t1);
s2.push(t2);
// Loop to iterate over the stacks
while (!s1.empty() && !s2.empty()) {
temp1 = s1.top();
temp2 = s2.top();
s1.pop();
s2.pop();
// Both are None
// hence they are equal
if (temp1 == NULL &&
temp2 == NULL)
continue;
// nodes are unequal
if ((temp1 == NULL && temp2 != NULL) ||
(temp1 != NULL && temp2 == NULL))
return false;
// nodes have unequal data
if (temp1->data != temp2->data)
return false;
s1.push(temp1->right);
s2.push(temp2->right);
s1.push(temp1->left);
s2.push(temp2->left);
}
// if both tree are identical
// both stacks must be empty.
if (s1.empty() && s2.empty())
return true;
else
return false;
}
// Function to check if the Tree s
// is the subtree of the Tree T
bool isSubTree(Node* s, Node* t)
{
// first we find the root of s in t
// by traversing in pre order fashion
stack<Node*> stk;
Node* temp;
stk.push(t);
while (!stk.empty()) {
temp = stk.top();
stk.pop();
// if current node data is equal
// to root of s then
if (temp->data == s->data) {
if (areTreeIdentical(s, temp))
return true;
}
if (temp->right)
stk.push(temp->right);
if (temp->left)
stk.push(temp->left);
}
return false;
}
// Driver Code
int main()
{
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
/*
2
/ \
4 5
*/
Node* root2 = newNode(2);
root2->left = newNode(4);
root2->right = newNode(5);
if (isSubTree(root2, root))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation to check
// if a tree is a subtree of
// another binary tree
import java.util.*;
class GFG{
// Structure of the
// binary tree node
static class Node {
int data;
Node left;
Node right;
};
// Function to create
// new node
static Node newNode(int x)
{
Node temp = new Node();
temp.data = x;
temp.left = null;
temp.right = null;
return temp;
}
// Function to check if two trees
// have same pre-order traversal
static boolean areTreeIdentical(Node t1, Node t2)
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
Node temp1;
Node temp2;
s1.add(t1);
s2.add(t2);
// Loop to iterate over the stacks
while (!s1.isEmpty() && !s2.isEmpty()) {
temp1 = s1.peek();
temp2 = s2.peek();
s1.pop();
s2.pop();
// Both are None
// hence they are equal
if (temp1 == null &&
temp2 == null)
continue;
// nodes are unequal
if ((temp1 == null && temp2 != null) ||
(temp1 != null && temp2 == null))
return false;
// nodes have unequal data
if (temp1.data != temp2.data)
return false;
s1.add(temp1.right);
s2.add(temp2.right);
s1.add(temp1.left);
s2.add(temp2.left);
}
// if both tree are identical
// both stacks must be empty.
if (s1.isEmpty() && s2.isEmpty())
return true;
else
return false;
}
// Function to check if the Tree s
// is the subtree of the Tree T
static boolean isSubTree(Node s, Node t)
{
// first we find the root of s in t
// by traversing in pre order fashion
Stack<Node> stk = new Stack<Node>();
Node temp;
stk.add(t);
while (!stk.isEmpty()) {
temp = stk.peek();
stk.pop();
// if current node data is equal
// to root of s then
if (temp.data == s.data) {
if (areTreeIdentical(s, temp))
return true;
}
if (temp.right != null)
stk.add(temp.right);
if (temp.left != null)
stk.add(temp.left);
}
return false;
}
// Driver Code
public static void main(String[] args)
{
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
/*
2
/ \
4 5
*/
Node root2 = newNode(2);
root2.left = newNode(4);
root2.right = newNode(5);
if (isSubTree(root2, root))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation to check
# if a tree is a subtree of
# another binary tree
# Structure of the
# binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to check if two trees
# have same pre-order traversal
def areTreeIdentical(t1 : Node,
t2 : Node) -> bool:
s1 = []
s2 = []
s1.append(t1)
s2.append(t2)
# Loop to iterate
# over the stacks
while s1 and s2:
temp1 = s1.pop()
temp2 = s2.pop()
# Both are None
# hence they are equal
if (temp1 is None and
temp2 is None):
continue
# Nodes are unequal
if ((temp1 is None and
temp2 is not None) or
(temp1 is not None and
temp2 is None)):
return False
# Nodes have unequal data
if (temp1.data != temp2.data):
return False
s1.append(temp1.right)
s2.append(temp2.right)
s1.append(temp1.left)
s2.append(temp2.left)
# If both tree are identical
# both stacks must be empty.
if s1 and s2:
return False
return True
# Function to check if the Tree s
# is the subtree of the Tree T
def isSubTree(s : Node,
t : Node) -> Node:
# First we find the
# root of s in t
# by traversing in
# pre order fashion
stk = []
stk.append(t)
while stk:
temp = stk.pop()
# If current node data is equal
# to root of s then
if (temp.data == s.data):
if (areTreeIdentical(s, temp)):
return True
if (temp.right):
stk.append(temp.right)
if (temp.left):
stk.append(temp.left)
return False
# Driver Code
if __name__ == "__main__":
'''
1
/ \
2 3
/ \ / \
4 5 6 7
'''
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
'''
2
/ \
4 5
'''
root2 = Node(2)
root2.left = Node(4)
root2.right = Node(5)
if (isSubTree(root2, root)):
print("Yes")
else:
print("No")
# This code is contributed by sanjeev2552
C#
// C# implementation to check
// if a tree is a subtree of
// another binary tree
using System;
using System.Collections.Generic;
class GFG{
// Structure of the
// binary tree node
class Node {
public int data;
public Node left;
public Node right;
};
// Function to create
// new node
static Node newNode(int x)
{
Node temp = new Node();
temp.data = x;
temp.left = null;
temp.right = null;
return temp;
}
// Function to check if two trees
// have same pre-order traversal
static bool areTreeIdentical(Node t1, Node t2)
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
Node temp1;
Node temp2;
s1.Push(t1);
s2.Push(t2);
// Loop to iterate over the stacks
while (s1.Count != 0 && s2.Count != 0) {
temp1 = s1.Peek();
temp2 = s2.Peek();
s1.Pop();
s2.Pop();
// Both are None
// hence they are equal
if (temp1 == null &&
temp2 == null)
continue;
// nodes are unequal
if ((temp1 == null && temp2 != null) ||
(temp1 != null && temp2 == null))
return false;
// nodes have unequal data
if (temp1.data != temp2.data)
return false;
s1.Push(temp1.right);
s2.Push(temp2.right);
s1.Push(temp1.left);
s2.Push(temp2.left);
}
// if both tree are identical
// both stacks must be empty.
if (s1.Count == 0 && s2.Count == 0)
return true;
else
return false;
}
// Function to check if the Tree s
// is the subtree of the Tree T
static bool isSubTree(Node s, Node t)
{
// first we find the root of s in t
// by traversing in pre order fashion
Stack<Node> stk = new Stack<Node>();
Node temp;
stk.Push(t);
while (stk.Count != 0) {
temp = stk.Peek();
stk.Pop();
// if current node data is equal
// to root of s then
if (temp.data == s.data) {
if (areTreeIdentical(s, temp))
return true;
}
if (temp.right != null)
stk.Push(temp.right);
if (temp.left != null)
stk.Push(temp.left);
}
return false;
}
// Driver Code
public static void Main(String[] args)
{
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
/*
2
/ \
4 5
*/
Node root2 = newNode(2);
root2.left = newNode(4);
root2.right = newNode(5);
if (isSubTree(root2, root))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// Javascript implementation to check
// if a tree is a subtree of
// another binary tree
// Structure of the
// binary tree node
class Node
{
constructor()
{
this.data = 0;
this.left = null;
this.right = null;
}
};
// Function to create
// new node
function newNode(x)
{
var temp = new Node();
temp.data = x;
temp.left = null;
temp.right = null;
return temp;
}
// Function to check if two trees
// have same pre-order traversal
function areTreeIdentical(t1, t2)
{
var s1 = [];
var s2 = [];
var temp1 = null;
var temp2 = null;
s1.push(t1);
s2.push(t2);
// Loop to iterate over the stacks
while (s1.length != 0 && s2.length != 0)
{
temp1 = s1[s1.length - 1];
temp2 = s2[s2.length - 1];
s1.pop();
s2.pop();
// Both are None
// hence they are equal
if (temp1 == null &&
temp2 == null)
continue;
// Nodes are unequal
if ((temp1 == null && temp2 != null) ||
(temp1 != null && temp2 == null))
return false;
// Nodes have unequal data
if (temp1.data != temp2.data)
return false;
s1.push(temp1.right);
s2.push(temp2.right);
s1.push(temp1.left);
s2.push(temp2.left);
}
// If both tree are identical
// both stacks must be empty.
if (s1.length == 0 && s2.length == 0)
return true;
else
return false;
}
// Function to check if the Tree s
// is the subtree of the Tree T
function isSubTree(s, t)
{
// First we find the root of s in t
// by traversing in pre order fashion
var stk = [];
var temp;
stk.push(t);
while (stk.length != 0)
{
temp = stk[stk.length - 1];
stk.pop();
// If current node data is equal
// to root of s then
if (temp.data == s.data)
{
if (areTreeIdentical(s, temp))
return true;
}
if (temp.right != null)
stk.push(temp.right);
if (temp.left != null)
stk.push(temp.left);
}
return false;
}
// Driver Code
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
var root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
/*
2
/ \
4 5
*/
var root2 = newNode(2);
root2.left = newNode(4);
root2.right = newNode(5);
if (isSubTree(root2, root))
document.write("Yes");
else
document.write("No");
// This code is contributed by rutvik_56
</script>
Time complexity: O(N) where N is no of nodes in a binary tree
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem