DSA Series Chapter 26 – Check if Two Binary Trees are Identical (Python Version)

 

[JOIN HERE] for daily coding insights

DSA Series Chapter 26 – Check if Two Binary Trees are Identical (Python Version)


1. Objective

To check whether two given binary trees are identical, i.e.:

  • Same structure

  • Same data at corresponding nodes


2. Definition (Exam-Oriented)

Two binary trees are identical if they have the same shape and same node values at every corresponding position.


3. When Are Two Trees Identical?

Two trees T1 and T2 are identical if:

  1. Both trees are empty

  2. Root values are equal

  3. Left subtrees are identical

  4. Right subtrees are identical

All four conditions must be true.


4. Visual Example

Identical Trees

        10                10
       /  \              /  \
      5   20            5   20

Not Identical

        10                10
       /                    \
      5                     5

5. Why Recursion Is Used

  • Binary trees are recursive data structures

  • Each subtree is itself a binary tree

  • Recursion naturally compares:

    • Current node

    • Left subtree

    • Right subtree


6. Node Structure (Python Class)

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

Explanation

  • data → stores node value

  • left → reference to left child

  • right → reference to right child


7. Logic to Check Identical Trees

Step-by-step logic:

If both nodes are None → identical
If one node is None → not identical
If data differs → not identical
Else:
    compare left subtrees
    compare right subtrees

8. Function to Check Identical Trees

def are_identical(root1, root2):
    if root1 is None and root2 is None:
        return True

    if root1 is None or root2 is None:
        return False

    if root1.data != root2.data:
        return False

    return (are_identical(root1.left, root2.left) and
            are_identical(root1.right, root2.right))

9. Line-by-Line Explanation

if root1 is None and root2 is None:
    return True
  • Both trees are empty at this position

  • Hence identical


if root1 is None or root2 is None:
    return False
  • One tree has a node, the other does not

  • Structure mismatch


if root1.data != root2.data:
    return False
  • Node values differ


return (are_identical(root1.left, root2.left) and
        are_identical(root1.right, root2.right))
  • Recursively compare:

    • Left subtrees

    • Right subtrees

  • and ensures both must match


10. Complete Python Program

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def are_identical(root1, root2):
    if root1 is None and root2 is None:
        return True

    if root1 is None or root2 is None:
        return False

    if root1.data != root2.data:
        return False

    return (are_identical(root1.left, root2.left) and
            are_identical(root1.right, root2.right))

# -------- Main --------
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)

root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)

if are_identical(root1, root2):
    print("Both trees are IDENTICAL")
else:
    print("Trees are NOT identical")

11. Output

Both trees are IDENTICAL

12. Time and Space Complexity

Time Complexity

  • O(n)
    (Each node compared once)

Space Complexity

  • O(h)
    (Recursive stack, where h is height of tree)


13. Key Differences: C vs Python

AspectCPython
NULLNULLNone
Return typeint (0/1)True / False
Structurestructclass
Memorymalloc()Automatic

14. Common Mistakes Students Make

  • Comparing only inorder traversal

  • Ignoring structure

  • Missing base case

  • Using or instead of and


15. Exam & Interview Tip

Traversal comparison alone is NOT sufficient
Structure + Data comparison is mandatory.

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)


DSA Series Chapter 2 Arrays  (Python Version)

DSA Series Chapter 3 Strings (C Version)


DSA Series Chapter 3 Strings (Python Version)


DSA Series Chapter 4 Linked Lists (Python Version)


DSA Series Chapter 4 Linked Lists (C Version)


DSA Series Chapter 5 Stacks (Python Version)


DSA Series Chapter 5  Stacks  (C Version)




















DSA Series Chapter 13 - Binary Tree traversal, BFS, DFT/DFS, Preorder Traversal In Binary Tree


DSA Series Chapter 14 - InOrder Traversal (Binary Tree C Version)


DSA Series Chapter 14 - InOrder Traversal (Binary Tree Python Version)

 

DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(Python Version)


DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(Python Version)



DSA Series Chapter 19 : DELETION IN BINARY TREE(C Version)

DSA Series Chapter 19 : DELETION IN BINARY TREE(Python Version)


DSA Series Chapter 20 – HEIGHT OF BINARY TREE(C Version)

DSA Series Chapter 20 – HEIGHT OF BINARY TREE(Python Version)

DSA Series Chapter 21 : COUNT TOTAL NODES IN BINARY TREE(C Version)

DSA Series Chapter 21 : COUNT TOTAL NODES IN BINARY TREE(Python Version)













Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights

Comments