Bird
Raised Fist0
DSA Cprogramming

Check if Two Trees are Symmetric in DSA C

Choose your learning style10 modes available
Mental Model
Two trees are symmetric if one is the mirror image of the other. We check this by comparing nodes in opposite positions.
Analogy: Imagine folding a paper with a tree drawn on each side. If the two trees match perfectly when folded, they are symmetric.
    Tree1           Tree2
      1                1
     / \              / \
    2   3            3   2
   /                  \ 
  4                    4

Pointers compare nodes across the fold like 2 with 2, 3 with 3, 4 with 4.
Dry Run Walkthrough
Input: Tree1: 1->2,3->4 (left child of 2), Tree2: 1->3,2->4 (right child of 2)
Goal: Check if Tree2 is the mirror image of Tree1
Step 1: Compare root nodes 1 and 1
Tree1: 1 ↑ -> 2 -> 3
Tree2: 1 ↑ -> 3 -> 2
Why: Roots must be equal to start symmetry check
Step 2: Compare left child of Tree1 (2) with right child of Tree2 (2)
Tree1: 2 ↑ -> 4
Tree2: 2 ↑ -> 4
Why: Mirror nodes must match in value
Step 3: Compare right child of Tree1 (3) with left child of Tree2 (3)
Tree1: 3 ↑ null
Tree2: 3 ↑ null
Why: Mirror nodes must match in value and structure
Step 4: Compare left child of 2 (4) with right child of 2 (4)
Tree1: 4 ↑ null
Tree2: 4 ↑ null
Why: Leaves must match to confirm symmetry
Result:
Trees are symmetric because all mirrored nodes match in value and structure
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Define tree node structure
typedef struct Node {
    int val;
    struct Node* left;
    struct Node* right;
} Node;

// Create new node
Node* newNode(int val) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->val = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Check if two trees are mirror images
int isMirror(Node* t1, Node* t2) {
    if (t1 == NULL && t2 == NULL) return 1; // both empty
    if (t1 == NULL || t2 == NULL) return 0; // one empty
    if (t1->val != t2->val) return 0; // values differ
    // check mirror: left of t1 vs right of t2 and right of t1 vs left of t2
    return isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
}

int main() {
    // Build Tree1
    Node* root1 = newNode(1);
    root1->left = newNode(2);
    root1->right = newNode(3);
    root1->left->left = newNode(4);

    // Build Tree2
    Node* root2 = newNode(1);
    root2->left = newNode(3);
    root2->right = newNode(2);
    root2->right->left = newNode(4);

    if (isMirror(root1, root2)) {
        printf("Trees are symmetric\n");
    } else {
        printf("Trees are not symmetric\n");
    }
    return 0;
}
if (t1 == NULL && t2 == NULL) return 1;
both nodes empty means symmetry at this branch
if (t1 == NULL || t2 == NULL) return 0;
one node empty means asymmetry
if (t1->val != t2->val) return 0;
values must match for symmetry
return isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
recursively check mirror positions
OutputSuccess
Trees are symmetric
Complexity Analysis
Time: O(n) because we visit each node once to compare
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Compared to flattening trees to arrays and reversing, this is more efficient and uses less space
Edge Cases
Both trees empty
Returns symmetric (true) because empty trees are mirrors
DSA C
if (t1 == NULL && t2 == NULL) return 1;
One tree empty, other not
Returns not symmetric (false)
DSA C
if (t1 == NULL || t2 == NULL) return 0;
Trees with different values at mirror positions
Returns not symmetric (false)
DSA C
if (t1->val != t2->val) return 0;
When to Use This Pattern
When a problem asks if two trees are mirror images or symmetric, use the mirror recursion pattern comparing opposite children.
Common Mistakes
Mistake: Comparing left child with left child and right with right instead of cross comparison
Fix: Compare left child of one tree with right child of the other and vice versa
Mistake: Not checking for null nodes before accessing values
Fix: Add null checks before value comparison to avoid errors
Summary
Checks if two trees are mirror images by recursively comparing opposite children.
Use when you need to verify if one tree is symmetric to another or itself.
The key is to compare left subtree of one tree with right subtree of the other and vice versa.

Practice

(1/5)
1. What does it mean for two binary trees to be symmetric?
easy
A. They are mirror images of each other around their roots
B. They have the same number of nodes
C. They have the same preorder traversal
D. They have the same height

Solution

  1. Step 1: Understand symmetry in trees

    Two trees are symmetric if one is the mirror reflection of the other around their roots.
  2. Step 2: Compare with other options

    Having the same number of nodes, preorder traversal, or height does not guarantee mirror symmetry.
  3. Final Answer:

    They are mirror images of each other around their roots -> Option A
  4. Quick Check:

    Symmetry means mirror image = A [OK]
Hint: Symmetric trees mirror each other around the root [OK]
Common Mistakes:
  • Confusing same size with symmetry
  • Thinking same traversal means symmetric
  • Assuming same height means symmetric
2. Which of the following C function signatures is correct to check if two trees are symmetric?
easy
A. int isSymmetric(struct Node* root1, struct Node* root2);
B. void isSymmetric(struct Node root1, struct Node root2);
C. int isSymmetric(struct Node root1, struct Node root2);
D. int isSymmetric(Node* root1, Node root2);

Solution

  1. Step 1: Understand pointer usage in C for trees

    Tree nodes are accessed via pointers, so parameters must be pointers to struct Node.
  2. Step 2: Analyze each option

    int isSymmetric(struct Node* root1, struct Node* root2); uses pointers correctly and returns int for boolean result. Options A and B pass structs by value, which is inefficient and incorrect. int isSymmetric(Node* root1, Node root2); mixes pointer and non-pointer types incorrectly.
  3. Final Answer:

    int isSymmetric(struct Node* root1, struct Node* root2); -> Option A
  4. Quick Check:

    Use pointers for tree nodes in C function [OK]
Hint: Use pointers to struct Node for tree parameters [OK]
Common Mistakes:
  • Passing structs by value instead of pointers
  • Mixing pointer and non-pointer parameters
  • Using void return type instead of int for boolean
3. What will be the output of the following code snippet checking symmetry of two trees?
struct Node {
  int val;
  struct Node* left;
  struct Node* right;
};

int isMirror(struct Node* t1, struct Node* t2) {
  if (!t1 && !t2) return 1;
  if (!t1 || !t2) return 0;
  return (t1->val == t2->val) && isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
}

int main() {
  struct Node n1 = {1, NULL, NULL};
  struct Node n2 = {1, NULL, NULL};
  printf("%d", isMirror(&n1, &n2));
  return 0;
}
medium
A. 0
B. 1
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Analyze base cases and node values

    Both nodes have value 1 and no children, so both left and right pointers are NULL.
  2. Step 2: Evaluate recursive calls

    isMirror returns 1 if both nodes are NULL (true). Since both left and right children are NULL, recursive calls return 1. Values match, so overall returns 1.
  3. Final Answer:

    1 -> Option B
  4. Quick Check:

    Identical single nodes are symmetric = 1 [OK]
Hint: Single nodes with same value are symmetric [OK]
Common Mistakes:
  • Confusing NULL children as asymmetric
  • Expecting 0 for identical nodes
  • Misreading recursive base cases
4. Identify the bug in this function to check if two trees are symmetric:
int isMirror(struct Node* t1, struct Node* t2) {
  if (t1 == NULL && t2 == NULL) return 1;
  if (t1 == NULL || t2 == NULL) return 0;
  if (t1->val != t2->val) return 0;
  return isMirror(t1->left, t2->left) && isMirror(t1->right, t2->right);
}
medium
A. Should use OR instead of AND in return statement
B. Missing check for NULL nodes
C. Return type should be void
D. Should compare t1->left with t2->right and t1->right with t2->left

Solution

  1. Step 1: Understand mirror symmetry check

    Mirror symmetry requires left subtree of one tree to match right subtree of the other and vice versa.
  2. Step 2: Identify incorrect recursive calls

    The code compares left with left and right with right, which checks for identical trees, not mirror symmetry.
  3. Final Answer:

    Should compare t1->left with t2->right and t1->right with t2->left -> Option D
  4. Quick Check:

    Mirror means cross compare left and right subtrees [OK]
Hint: Mirror check swaps left and right subtrees [OK]
Common Mistakes:
  • Comparing left with left and right with right
  • Ignoring NULL checks
  • Using wrong logical operators
5. Given two binary trees, how would you implement a function to check if they are symmetric using a queue (iterative approach)? Which step is essential in this approach?
hard
A. Compare only root nodes and ignore children
B. Traverse both trees in preorder and compare arrays
C. Enqueue pairs of nodes to compare left of one with right of other
D. Use a stack to store nodes from only one tree

Solution

  1. Step 1: Understand iterative symmetry check

    Use a queue to store pairs of nodes to compare their values and subtrees iteratively.
  2. Step 2: Identify correct node pairing

    Pairs must be left child of one tree with right child of the other to check mirror symmetry.
  3. Step 3: Reject incorrect approaches

    Preorder traversal comparison or using stack for one tree only does not check mirror symmetry. Ignoring children misses the point.
  4. Final Answer:

    Enqueue pairs of nodes to compare left of one with right of other -> Option C
  5. Quick Check:

    Queue pairs left-right nodes for iterative mirror check [OK]
Hint: Queue pairs left and right nodes to check symmetry iteratively [OK]
Common Mistakes:
  • Comparing same side children instead of opposite
  • Using preorder traversal arrays
  • Ignoring children nodes in comparison
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard