Open In App

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

Last Updated : 21 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
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)



Similar Reads

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, we need to write a program 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 general binary tree using these two traver
12 min read
Iterative Preorder Traversal
Given a Binary Tree, write an iterative function to print the Preorder traversal of the given binary tree.Refer to this for recursive preorder traversal of Binary Tree. To convert an inherently recursive procedure to iterative, we need an explicit stack. Following is a simple stack based iterative process to print Preorder traversal. Create an empt
15+ 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 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. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
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 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. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
12 min read
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 subtree.For example, in the following case, Tree1 i
15+ min read
Find postorder traversal of BST from preorder traversal
Given an array representing preorder traversal of BST, print its postorder traversal. Examples: Input : 40 30 35 80 100 Output : 35 30 100 80 40 Input : 40 30 32 35 80 90 100 120 Output : 35 32 30 120 100 90 80 40 Prerequisite: Construct BST from given preorder traversal Simple Approach: A simple solution is to first construct BST from a given preo
9 min read
Check if a given array can represent Preorder Traversal of Binary Search Tree
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n). Examples: Input: pre[] = {2, 4, 3} Output: true Given array can represent preorder traversal of below tree 2 \ 4 / 3 Input: pre[] = {2, 4, 1} Output: false Given array cannot represent
15 min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 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 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Find n-th node in Preorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Preorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input: N = 4 11 / \ 21 31 / \ 41 51 Output: 51 Explanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31, so 4th node will be 51. Input: N = 5 25 / \ 20 30 / \ / \ 18 22 24
6 min read
Practice Tags :
three90RightbarBannerImg