Check if two trees have same structure - GeeksforGeeks

08 Apr, 2022
Given two binary trees. The task is to write a program to check if the two trees are identical in structure. 
In the above figure both of the trees, Tree1 and Tree2 are identical in structure. That is, they have the same structure.Note: This problem is different from Check if two trees are identical as here we need to compare only the structures of the two trees and not the values at their nodes. 
The idea is to traverse both trees simultaneously following the same paths and keep checking if a node exists for both the trees or not.Algorithm:  
If both trees are empty then return 1.Else If both trees are non-empty: Check left subtrees recursively i.e., call isSameStructure(tree1->left_subtree, tree2->left_subtree)Check right subtrees recursively i.e., call isSameStructure(tree1->right_subtree, tree2->right_subtree)If the value returned in above two steps are true then return 1.Else return 0 (one is empty and other is not).
If both trees are empty then return 1.
Else If both trees are non-empty: Check left subtrees recursively i.e., call isSameStructure(tree1->left_subtree, tree2->left_subtree)Check right subtrees recursively i.e., call isSameStructure(tree1->right_subtree, tree2->right_subtree)If the value returned in above two steps are true then return 1.
Check left subtrees recursively i.e., call isSameStructure(tree1->left_subtree, tree2->left_subtree)
Check right subtrees recursively i.e., call isSameStructure(tree1->right_subtree, tree2->right_subtree)
If the value returned in above two steps are true then return 1.
Else return 0 (one is empty and other is not).
Below is the implementation of above algorithm:  
C++
C
Java
Python3
C#
Javascript
// C++ program to check if two trees have// same structure#include <iostream>using namespace std; // A binary tree node has data, pointer to left child// and a pointer to right childstruct Node{    int data;    struct Node* left;    struct Node* right;}; // 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);} // Function to check if two trees have same// structureint isSameStructure(Node* a, Node* b){    // 1. both empty    if (a==NULL && b==NULL)        return 1;    // 2. both non-empty -> compare them    if (a!=NULL && b!=NULL)    {        return        (            isSameStructure(a->left, b->left) &&            isSameStructure(a->right, b->right)        );    }    // 3. one empty, one not -> false    return 0;} // Driver codeint main(){    Node *root1 = newNode(10);    Node *root2 = newNode(100);    root1->left = newNode(7);    root1->right = newNode(15);    root1->left->left = newNode(4);    root1->left->right = newNode(9);    root1->right->right = newNode(20);     root2->left = newNode(70);    root2->right = newNode(150);    root2->left->left = newNode(40);    root2->left->right = newNode(90);    root2->right->right = newNode(200);     if (isSameStructure(root1, root2))        printf("Both trees have same structure");    else        printf("Trees do not have same structure");    return 0;} // This code is contributed by aditya kumar (adityakumar129)
// C++ program to check if two trees have// same structure#include <stdio.h>#include <stdlib.h> // A binary tree node has data, pointer to left child// and a pointer to right childtypedef struct Node {    int data;    struct Node* left;    struct Node* right;} Node; // Helper function that allocates a new node with the// given data and NULL left and right pointers.Node* newNode(int data){    Node* node = (Node*)malloc(sizeof(Node));    node->data = data;    node->left = NULL;    node->right = NULL;    return (node);} // Function to check if two trees have same// structureint isSameStructure(Node* a, Node* b){    // 1. both empty    if (a == NULL && b == NULL)        return 1;    // 2. both non-empty -> compare them    if (a != NULL && b != NULL) {        return (isSameStructure(a->left, b->left)                && isSameStructure(a->right, b->right));    }    // 3. one empty, one not -> false    return 0;} // Driver codeint main(){    Node* root1 = newNode(10);    Node* root2 = newNode(100);    root1->left = newNode(7);    root1->right = newNode(15);    root1->left->left = newNode(4);    root1->left->right = newNode(9);    root1->right->right = newNode(20);     root2->left = newNode(70);    root2->right = newNode(150);    root2->left->left = newNode(40);    root2->left->right = newNode(90);    root2->right->right = newNode(200);     if (isSameStructure(root1, root2))        printf("Both trees have same structure");    else        printf("Trees do not have same structure");    return 0;} // This code is contributed by aditya kumar (adityakumar129)
// Java program to check if two trees have// same structureclass GFG{     // A binary tree node has data,// pointer to left child and// a pointer to right childstatic class Node{    int data;    Node left;    Node right;}; // Helper function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return(node);} // Function to check if two trees// have same structurestatic boolean isSameStructure(Node a, Node b){    // 1. both empty    if (a == null && b == null)        return true;     // 2. both non-empty . compare them    if (a != null && b != null)    {        return        (            isSameStructure(a.left, b.left) &&            isSameStructure(a.right, b.right)        );    }         // 3. one empty, one not . false    return false;} // Driver codepublic static void main(String args[]){    Node root1 = newNode(10);    Node root2 = newNode(100);    root1.left = newNode(7);    root1.right = newNode(15);    root1.left.left = newNode(4);    root1.left.right = newNode(9);    root1.right.right = newNode(20);     root2.left = newNode(70);    root2.right = newNode(150);    root2.left.left = newNode(40);    root2.left.right = newNode(90);    root2.right.right = newNode(200);     if (isSameStructure(root1, root2))        System.out.printf("Both trees have same structure");    else        System.out.printf("Trees do not have same structure");}} // This code is contributed by Arnab Kundu
# Python3 program to check if two trees have# same structure  # A binary tree node has data, pointer to left child# and a pointer to right childclass Node:         def __init__(self, data):                 self.left = None        self.right = None        self.data = data # Helper function that allocates a new node with the# given data and None left and right pointers.def newNode(data):         node = Node(data)    return node     # Function to check if two trees have same# structuredef isSameStructure(a, b):     # 1. both empty    if (a == None and b == None):        return 1;      # 2. both non-empty . compare them    if (a != None and b != None):             return (            isSameStructure(a.left, b.left) and            isSameStructure(a.right, b.right))             # 3. one empty, one not . false    return 0;  # Driver codeif __name__=='__main__':         root1 = newNode(10);    root2 = newNode(100);    root1.left = newNode(7);    root1.right = newNode(15);    root1.left.left = newNode(4);    root1.left.right = newNode(9);    root1.right.right = newNode(20);      root2.left = newNode(70);    root2.right = newNode(150);    root2.left.left = newNode(40);    root2.left.right = newNode(90);    root2.right.right = newNode(200);      if (isSameStructure(root1, root2)):        print("Both trees have same structure");    else:        print("Trees do not have same structure");  # This code is contributed by rutvik_56
// C# program to check if two trees// have same structureusing System; class GFG{     // A binary tree node has data,// pointer to left child and// a pointer to right childpublic class Node{    public int data;    public Node left;    public Node right;}; // Helper function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;     return(node);} // Function to check if two trees// have same structurestatic Boolean isSameStructure(Node a,                               Node b){    // 1. both empty    if (a == null && b == null)        return true;     // 2. both non-empty . compare them    if (a != null && b != null)    {        return        (            isSameStructure(a.left, b.left) &&            isSameStructure(a.right, b.right)        );    }         // 3. one empty, one not . false    return false;} // Driver codepublic static void Main(String []args){    Node root1 = newNode(10);    Node root2 = newNode(100);    root1.left = newNode(7);    root1.right = newNode(15);    root1.left.left = newNode(4);    root1.left.right = newNode(9);    root1.right.right = newNode(20);     root2.left = newNode(70);    root2.right = newNode(150);    root2.left.left = newNode(40);    root2.left.right = newNode(90);    root2.right.right = newNode(200);     if (isSameStructure(root1, root2))        Console.Write("Both trees have " +                       "same structure");    else        Console.Write("Trees do not have" +                      " same structure");}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to check if two trees// have same structure   // A binary tree node has data,// pointer to left child and// a pointer to right childclass Node{  constructor()  {    this.data = 0;    this.left = null;    this.right = null;  }}; // Helper function that allocates a new node// with the given data and null left// and right pointers.function newNode(data){    var node = new Node();    node.data = data;    node.left = null;    node.right = null;    return node;} // Function to check if two trees// have same structurefunction isSameStructure(a, b){    // 1. both empty    if (a == null && b == null)        return true;     // 2. both non-empty . compare them    if (a != null && b != null)    {        return isSameStructure(a.left, b.left) &&        isSameStructure(a.right, b.right) ;    }         // 3. one empty, one not . false    return false;} // Driver codevar root1 = newNode(10);var root2 = newNode(100);root1.left = newNode(7);root1.right = newNode(15);root1.left.left = newNode(4);root1.left.right = newNode(9);root1.right.right = newNode(20);root2.left = newNode(70);root2.right = newNode(150);root2.left.left = newNode(40);root2.left.right = newNode(90);root2.right.right = newNode(200);if (isSameStructure(root1, root2))    document.write("Both trees have " +                   "same structure");else    document.write("Trees do not have" +                  " same structure");  </script>
Both trees have same structure
 
andrew1234
Rajput-Ji
rutvik_56
noob2000
adityakumar129
Algorithms-Recursion
Binary Tree
Trees
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Queue | Question 11
Data Structures | Stack | Question 4
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Program to create Custom Vector Class in C++
Encryption and Decryption of String according to given technique
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion