DATA STRUCTURES PROGRAM • TREES & BINARY SEARCH TREES

Check Whether Two Binary Trees Are Identical

Learn how to check whether two binary trees are identical using a clear C program.

BeginnerBinary treeNodesRecursion

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Trees are identical.

COMPLETE C PROGRAM

Complete C implementation

dsa-identical-binary-trees.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct TreeNode { int data; struct TreeNode *left; struct TreeNode *right; };
struct TreeNode *new_node(int value)
{
    struct TreeNode *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->data = value; node->left = NULL; node->right = NULL;
    return node;
}
struct TreeNode *sample_tree(void)
{
    struct TreeNode *root = new_node(1);
    root->left = new_node(2); root->right = new_node(3);
    root->left->left = new_node(4); root->left->right = new_node(5);
    root->right->left = new_node(6); root->right->right = new_node(7);
    return root;
}
void free_tree(struct TreeNode *root)
{
    if (root == NULL) return;
    free_tree(root->left); free_tree(root->right); free(root);
}
int identical(struct TreeNode *first, struct TreeNode *second)
{
    if (first == NULL || second == NULL) return first == second;
    return first->data == second->data &&
           identical(first->left, second->left) &&
           identical(first->right, second->right);
}

int main(void)
{
    struct TreeNode *first = sample_tree();
    struct TreeNode *second = sample_tree();
    puts(identical(first, second) ? "Trees are identical." : "Trees differ.");
    free_tree(first); free_tree(second);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Trees are identical.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Require equal values and identical left and right subtree structure at every position.
  3. Display the computed result.

Require equal values and identical left and right subtree structure at every position.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(h)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.