The Wayback Machine - https://web.archive.org/web/20240920190040/https://www.geeksforgeeks.org/check-if-two-trees-have-same-structure/
Open In App

Check if two trees have same structure

Last Updated : 20 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. If both trees are empty then return 1.
  2. 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.
  3. Else return 0 (one is empty and other is not).

Below is the implementation of above algorithm:

C++




// 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 child
struct 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
// structure
int 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 code
int 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




// 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 child
typedef 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
// structure
int 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 code
int 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




// Java program to check if two trees have
// same structure
class GFG
{
     
// A binary tree node has data,
// pointer to left child and
// a pointer to right child
static 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 structure
static 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 code
public 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




# 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 child
class 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
# structure
def 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 code
if __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#




// C# program to check if two trees
// have same structure
using System;
 
class GFG
{
     
// A binary tree node has data,
// pointer to left child and
// a pointer to right child
public 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 structure
static 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 code
public 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


Javascript




<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 child
class 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 structure
function 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 code
var 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>


Output

Both trees have same structure

Time Complexity: O(N)
Auxiliary Space: O(N)



Similar Reads

Check if leaf traversal of two Binary Trees is same?
Leaf traversal is the sequence of leaves traversed from left to right. The problem is to check if the leaf traversals of two given Binary Trees are same or not.Expected time complexity O(n). Expected auxiliary space O(h1 + h2) where h1 and h2 are heights of two Binary Trees. Examples: Input: Roots of below Binary Trees 1 / \ 2 3 / / \ 4 6 7 0 / \ 5
15+ min read
Check if two numbers have same number of digits
Given two integers A and B, the task is to check whether both the numbers have an equal number of digits.Examples: Input: A = 12, B = 1 Output: NoInput: A = 20, B = 99 Output: Yes Approach: While both the numbers are &gt; 0, keep dividing both the numbers by 10. Finally, check if both the numbers are 0. If any one of them is not 0 then they had an
4 min read
Check whether two convex regular polygon have same center or not
Given two positive integers N and M which denotes the sides of the convex regular polygon where N &lt; M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each vertex of the polygon. Examples: Input: N = 9, M =
3 min read
Check if two unsorted arrays (with duplicates allowed) have same elements
Given two unsorted arrays, check whether both arrays have the same set of elements or not. Examples: Input : A = {2, 5, 6, 8, 10, 2, 2} B = {2, 5, 5, 6, 8, 5, 6} Output : No Input : A = {2, 5, 6, 8, 2, 10, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Input : A = {2, 5, 8, 6, 10, 2, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Method 1 (Simple):A simple
13 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Maximum subset sum such that no two elements in set have same digit in them
Given an array of N elements. Find the subset of elements which has maximum sum such that no two elements in the subset has common digit present in them.Examples: Input : array[] = {22, 132, 4, 45, 12, 223} Output : 268 Maximum Sum Subset will be = {45, 223} . All possible digits are present except 1. But to include 1 either 2 or both 2 and 3 have
12 min read
Minimum exchange such that no two adjacent Matrix cells have same character
Given a matrix of size N * M. Every cell of the matrix contains either 'A' or 'B'. Exchange is defined as swapping the characters between two cells. The task is to find the minimum number of exchanges needed to rearrange the given matrix such that no adjacent cell contains the same characters. Note: Two cells are adjacent if they share one of their
9 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Introduction to Generic Trees (N-ary Trees)
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes. Every node stores address of its children and the very first node's address will be stored in a s
5 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input : abbaab Output : NO The two ha
3 min read
Check if both halves of the string have same set of characters
Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input: abbaab Output: NO The two h
12 min read
Minimum number of additional Trees to have exactly n-leaf nodes
Given a tree with only one node. We want a tree with exactly n-leaf nodes. We have exactly k trees consisting of 1, 2, ..., and k leaf nodes. For example, we had k additional trees. The only operation we can do now is to superimpose the root of one of the additional trees onto any leave of the original tree. Determine the minimum number of addition
7 min read
Loss when two items are sold at same price and same percentage profit/loss
Given the Selling price i.e 'SP' of the two items each. One item is sold at 'P%' Profit and other at 'P%' Loss. The task is to find out the overall Loss.Examples: Input: SP = 2400, P = 30% Output: Loss = 474.725 Input: SP = 5000, P = 10% Output: Loss = 101.01 Approach: How does the above formula work? For profit making item : With selling price (10
4 min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Check if two trees are mirror of each other using level order traversal
Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not.Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Trees in the above figure are mirrors of each other. A recursive solution and an iterative method u
12 min read
Iterative Approach to check if two Binary Trees are Isomorphic or not
Given two Binary Trees we have to detect if the two trees are Isomorphic. Two trees are called isomorphic if one of them can be obtained from another by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Note: Two empty trees are isomorphic. For example
12 min read
Check if two binary trees are mirror | Set 3
Given two arrays, A[] and B[] consisting of M pairs, representing the edges of the two binary trees of N distinct nodes according to the level order traversal, the task is to check if trees are the mirror images of each other. Examples: Input: N = 6, M = 5, A[][2] = {{1, 5}, {1, 4}, {5, 7}, {5, 8}, {4, 9}}, B[][2] = {{1, 4}, {1, 5}, {4, 9}, {5, 8},
10 min read
Check if two Binary trees are identical after exactly K changes
Given two binary trees T1 and T2 and integer K, the task is to check whether both trees are identical or not after making exactly K changes in the first tree. In each change, one tree element can be converted into any other integer. Examples: Input: K = 1 T1 = 1 T2 = 1 / \ / \ 2 4 2 3Output: YesExplanation: Change the node with value 4 to value 3 I
9 min read
Check if two trees are Mirror
Given two Binary Trees, write a function that returns true if two trees are mirror of each other, else false. For example, the function should return true for following input trees.  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.  This problem is different from the problem discussed here.For two trees 'a' and '
14 min read
Iterative function to check if two trees are identical
Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Examples: Input : Roots of below trees 10 10 / \ / 5 6 5 Output : falseInput : Roots of below trees 10 1
15+ min read
Iterative method to check if two trees are mirror of each other
Given two binary trees. The problem is to check whether the two binary trees are mirrors of each other or not. Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Trees in the above figure are mirrors of each other. Recommended PracticeTwo Mirror TreesTry It
11 min read
Check if two trees are Mirror | Set 2
Given two Binary Trees, returns true if two trees are mirror of each other, else false. Mirror Tree : Previously discussed approach is here. Approach: Find the inorder traversal of both the Binary Trees, and check whether one traversal is reverse of another or not. If they are reverse of each other then the trees are mirror of each other, else not.
7 min read
Check if all levels of two trees are anagrams or not
Given two binary trees, we have to check if each of their levels is an anagram of the other or not. Example:    Tree 1:Level 0 : 1Level 1 : 3, 2Level 2 : 5, 4Tree 2:Level 0 : 1Level 1 : 2, 3Level 2 : 4, 5As we can clearly see all the levels of above two binary trees are anagrams of each other, hence return true. Recommended PracticeCheck if all lev
15+ min read
Number of distinct pair of edges such that it partitions both trees into same subsets of nodes
Given two trees each of N nodes. Removing an edge of the tree partitions the tree in two subsets.Find the total maximum number of distinct edges (e1, e2): e1 from the first tree and e2 from the second tree such that it partitions both the trees into subsets with same nodes. Examples:    Input : Same as the above figure N = 6 Tree 1 : {(1, 2), (2, 3
15 min read
Check if two strings have a common substring
You are given two strings str1 and str2. You have to check if the two strings share a common substring. Examples : Input : str1 = "HELLO" str2 = "WORLD" Output : YES Explanation : The substrings "O" and "L" are common to both str1 and str2 Input : str1 = "HI" str2 = "ALL" Output : NO Explanation : Because str1 and str2 have no common substrings A b
5 min read
Minimum colors required such that edges forming cycle do not have same color
Given a directed graph with V vertices and E edges without self-loops and multiple edges, the task is to find the minimum number of colors required such that edges of the same color do not form cycle and also find the colors for every edge.Examples: Input: V = {1, 2, 3}, E = {(1, 2), (2, 3), (3, 1)} Output: 2 1 1 2 Explanation: In the above given g
10 min read
Minimum number of socks required to picked to have at least K pairs of the same color
Given an array arr[] consisting of N integers such that arr[i] representing the number of socks of the color i and an integer K, the task is to find the minimum number of socks required to be picked to get at least K pairs of socks of the same color. Examples: Input: arr[] = {3, 4, 5, 3}, K = 6Output: 15Explanation: One will need to pick all the so
5 min read
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Given a positive integer N and an integer K such that 0 ≤ K ≤ N, the task is to find any permutation A of [1, N] such that the number of indices for which Ai = i is exactly K (1-based indexing). If there exists no such permutation, print −1. Examples: Input: N = 3, K = 1Output: 1 3 2Explanation: Consider the permutation A = [1, 3, 2]. We have A1=1,
5 min read