Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Check whether a binary tree is a full binary tree or not | Iterative Approach
Next article icon

Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative

Last Updated : 21 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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>  

Output: 
Yes

 

Time complexity: O(N) where N is no of nodes in a binary tree

Auxiliary Space: O(N)


Next Article
Check whether a binary tree is a full binary tree or not | Iterative Approach

K

Kashish_070250
Improve
Article Tags :
  • Tree
  • DSA
  • Preorder Traversal
  • Binary Tree
Practice Tags :
  • Tree

Similar Reads

  • Check if a binary tree is subtree of another binary tree | Set 2
    Given two binary trees, check if the first tree is a 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 s
    15+ min read
  • Check if a Binary Tree is subtree of another binary tree | Set 1
    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
    9 min read
  • Check if a Binary tree is Subtree of another Binary tree | Set 3
    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
    12 min read
  • Check whether a binary tree is a full binary tree or not | Iterative Approach
    Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one ch
    8 min read
  • Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
    Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input: level = [10, 15, 14, 25, 30]Output: TrueExplanation: The tree of the given level order traversal is We see that each parent has a value less than its child, and hence sat
    4 min read
  • Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
    Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, the task is to construct the binary tree using these two Preorder traversals. A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a genera
    9 min read
  • Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
    cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4,
    15+ min read
  • Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
    Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12
    9 min read
  • Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
    Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5
    13 min read
  • Check if the level order traversal of a Binary Tree results in a palindrome
    Given a binary tree. The task is to check if its level order traversal results in a palindrome or not. Examples: Input: Output: TrueExplanation: RADAR is the level order traversal of the given tree which is a palindrome. Input: Output: FalseExplanation: RADARS is the level order traversal of the giv
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences