Bird
Raised Fist0
DSA Cprogramming

Mirror a Binary Tree in DSA C

Choose your learning style10 modes available
Mental Model
Flipping a binary tree means swapping every left child with its right child, all the way down.
Analogy: Imagine holding a tree-shaped mirror and seeing the tree's reflection flipped left to right.
    1
   / \
  2   3
 / \
4   5
Dry Run Walkthrough
Input: Tree: 1 with left child 2 and right child 3; 2 has children 4 (left) and 5 (right)
Goal: Flip the tree so left and right children swap at every node
Step 1: Start at root node 1, swap its left and right children
    1
   / \
  3   2
     / \
    4   5
Why: Swapping children at root flips the top level
Step 2: Move to node 3, which has no children, so no swap needed
    1
   / \
  3   2
     / \
    4   5
Why: Leaf nodes have no children to swap
Step 3: Move to node 2, swap its left and right children 4 and 5
    1
   / \
  3   2
     / \
    5   4
Why: Swapping children at node 2 flips the subtree
Step 4: Move to node 5 and node 4, both leaves, no swaps needed
    1
   / \
  3   2
     / \
    5   4
Why: Leaves end recursion
Result:
    1
   / \
  3   2
     / \
    5   4
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

// Define a binary tree node
typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;

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

// Mirror the binary tree by swapping left and right children recursively
void mirror(Node* root) {
    if (root == NULL) return; // base case: empty node

    // swap left and right children
    Node* temp = root->left;
    root->left = root->right;
    root->right = temp;

    mirror(root->left);  // mirror left subtree
    mirror(root->right); // mirror right subtree
}

// Print tree in preorder to show structure
void preorderPrint(Node* root) {
    if (root == NULL) return;
    printf("%d ", root->data);
    preorderPrint(root->left);
    preorderPrint(root->right);
}

int main() {
    // Build tree: 1
    //           /   \
    //          2     3
    //         / \
    //        4   5
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

    printf("Original tree preorder: ");
    preorderPrint(root);
    printf("\n");

    mirror(root);

    printf("Mirrored tree preorder: ");
    preorderPrint(root);
    printf("\n");

    return 0;
}
if (root == NULL) return;
stop recursion at empty node
Node* temp = root->left; root->left = root->right; root->right = temp;
swap left and right children of current node
mirror(root->left);
recursively mirror left subtree
mirror(root->right);
recursively mirror right subtree
OutputSuccess
Original tree preorder: 1 2 4 5 3 Mirrored tree preorder: 1 3 2 5 4
Complexity Analysis
Time: O(n) because we visit every node once to swap children
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Iterative methods exist but recursion is simpler and intuitive for tree traversal
Edge Cases
Empty tree (root is NULL)
Function returns immediately without error
DSA C
if (root == NULL) return;
Tree with single node
No swaps happen, tree remains same
DSA C
if (root == NULL) return;
Tree with only left or only right children
Children get swapped correctly, flipping structure
DSA C
Node* temp = root->left; root->left = root->right; root->right = temp;
When to Use This Pattern
When asked to flip or invert a binary tree, use the mirror pattern by swapping children recursively to transform the tree.
Common Mistakes
Mistake: Forgetting to recurse on both left and right children after swapping
Fix: Call mirror recursively on both root->left and root->right after swapping
Mistake: Swapping children without checking for NULL nodes causing segmentation fault
Fix: Add base case to return immediately if root is NULL
Summary
It flips a binary tree by swapping every node's left and right children.
Use it when you need the mirror image of a binary tree.
The key is to swap children at each node and do this recursively down the tree.

Practice

(1/5)
1. What does mirroring a binary tree mean?
easy
A. Sorting the nodes in ascending order
B. Swapping the left and right children of every node in the tree
C. Removing all leaf nodes from the tree
D. Counting the total number of nodes in the tree

Solution

  1. Step 1: Understand the mirror operation

    Mirroring a binary tree means swapping the left and right children of every node.
  2. Step 2: Identify the effect on the tree

    This operation flips the tree around its center, creating a mirror image.
  3. Final Answer:

    Swapping the left and right children of every node in the tree -> Option B
  4. Quick Check:

    Mirror = Swap children [OK]
Hint: Mirror means swap left and right children at all nodes [OK]
Common Mistakes:
  • Thinking mirror means sorting nodes
  • Confusing mirror with deleting nodes
  • Assuming mirror counts nodes
2. Which of the following is the correct C function signature to mirror a binary tree node?
easy
A. void mirrorTree(struct Node* root);
B. int mirrorTree(struct Node root);
C. struct Node mirrorTree(struct Node* root);
D. void mirrorTree(struct Node root);

Solution

  1. Step 1: Understand parameter passing for trees in C

    Binary trees are usually passed as pointers to nodes to allow modification.
  2. Step 2: Identify correct return type

    Mirroring modifies the tree in place, so the function returns void.
  3. Final Answer:

    void mirrorTree(struct Node* root); -> Option A
  4. Quick Check:

    Pointer parameter + void return = void mirrorTree(struct Node* root); [OK]
Hint: Use pointer to root and void return for in-place mirror [OK]
Common Mistakes:
  • Passing struct Node by value instead of pointer
  • Returning struct Node instead of void
  • Using int return type incorrectly
3. What will be the output of the following code snippet after mirroring the binary tree?
struct Node {
  int data;
  struct Node* left;
  struct Node* right;
};

void mirrorTree(struct Node* root) {
  if (root == NULL) return;
  struct Node* temp = root->left;
  root->left = root->right;
  root->right = temp;
  mirrorTree(root->left);
  mirrorTree(root->right);
}

// Tree before mirror:
//     1
//    / \
//   2   3
//  /     \
// 4       5

// After mirror, print preorder traversal:
// Expected output?
medium
A. 1 2 3 4 5
B. 1 2 4 3 5
C. 1 3 2 5 4
D. 1 3 5 2 4

Solution

  1. Step 1: Understand the mirror operation on the tree

    Swapping left and right children at every node flips the tree: Original root 1 has left=2, right=3 After mirror: left=3, right=2 Node 2 has left=4, right=NULL After mirror: left=NULL, right=4 Node 3 has left=NULL, right=5 After mirror: left=5, right=NULL
  2. Step 2: Perform preorder traversal on mirrored tree

    Preorder: root, left, right Visit 1 Go left to 3 Go left to 5 (leaf) Back to 1, go right to 2 Go left NULL, go right 4 Sequence: 1 3 5 2 4
  3. Final Answer:

    1 3 5 2 4 -> Option D
  4. Quick Check:

    Mirror + preorder = 1 3 5 2 4 [OK]
Hint: Mirror swaps children; preorder visits root-left-right [OK]
Common Mistakes:
  • Not swapping children correctly
  • Confusing preorder with inorder or postorder
  • Missing leaf nodes in traversal
4. Identify the error in the following mirror function and select the fix:
void mirrorTree(struct Node* root) {
  if (root == NULL) return;
  mirrorTree(root->left);
  struct Node* temp = root->left;
  root->left = root->right;
  root->right = temp;
  mirrorTree(root->right);
}
medium
A. Add return type as int instead of void
B. Remove the base case check for NULL
C. Swap children before recursive calls to mirrorTree
D. Change temp to int instead of struct Node*

Solution

  1. Step 1: Analyze the order of operations in the function

    The function calls mirrorTree on left and right children before swapping them. This causes the recursive calls to work on original children, not swapped ones.
  2. Step 2: Correct the order to swap first, then recurse

    Swapping children first ensures recursive calls mirror the swapped subtrees correctly.
  3. Final Answer:

    Swap children before recursive calls to mirrorTree -> Option C
  4. Quick Check:

    Swap first, recurse later [OK]
Hint: Swap children before recursion to mirror correctly [OK]
Common Mistakes:
  • Swapping after recursion causes incorrect mirror
  • Removing base case causes crashes
  • Changing temp type breaks pointer logic
5. Given a binary tree where some nodes have only one child, what is the effect of mirroring the tree on the structure and leaf nodes? Choose the correct statement.
hard
A. All leaf nodes remain leaf nodes but their positions are mirrored
B. Some leaf nodes become internal nodes after mirroring
C. The number of leaf nodes doubles after mirroring
D. Mirroring removes all nodes with only one child

Solution

  1. Step 1: Understand mirroring effect on node positions

    Mirroring swaps left and right children but does not add or remove nodes. Leaf nodes remain leaf nodes but their positions flip left to right.
  2. Step 2: Confirm leaf nodes count and structure

    Number of leaf nodes stays the same; no nodes become internal or are removed. Only their left-right positions change.
  3. Final Answer:

    All leaf nodes remain leaf nodes but their positions are mirrored -> Option A
  4. Quick Check:

    Mirror flips positions, leaf count unchanged [OK]
Hint: Mirror flips positions, leaf nodes stay leaf nodes [OK]
Common Mistakes:
  • Thinking leaf nodes become internal nodes
  • Assuming nodes are added or removed
  • Believing leaf count changes
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