0
0
DSA C++programming~30 mins

Mirror a Binary Tree in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Mirror a Binary Tree
📖 Scenario: You are working with a simple binary tree structure used in many applications like file systems or decision trees. Sometimes, you need to create a mirror image of this tree, flipping it left to right.
🎯 Goal: Build a program that creates a binary tree, then writes a function to mirror it by swapping left and right children at every node, and finally prints the mirrored tree in order.
📋 What You'll Learn
Create a binary tree with exactly 5 nodes with these values: 1 (root), 2 (left child of root), 3 (right child of root), 4 (left child of node 2), 5 (right child of node 2)
Create a function called mirror that takes a pointer to the root node and swaps its left and right children recursively
Create a function called inorder that prints the tree nodes in inorder traversal separated by spaces
Print the inorder traversal of the mirrored tree
💡 Why This Matters
🌍 Real World
Mirroring trees is useful in graphics, image processing, and reversing decision trees for analysis.
💼 Career
Understanding tree manipulations is important for software engineers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the binary tree nodes
Create a struct called Node with an int data and two pointers left and right. Then create nodes with values 1, 2, 3, 4, and 5. Connect them to form this tree:
1 is root, 2 is left child of 1, 3 is right child of 1, 4 is left child of 2, 5 is right child of 2.
DSA C++
Hint

Define the Node struct with a constructor. Then create nodes and link them as described.

2
Create the mirror function
Create a function called mirror that takes a Node* called root. If root is not null, recursively call mirror on root->left and root->right, then swap root->left and root->right.
DSA C++
Hint

Use recursion to visit left and right children, then swap them.

3
Create the inorder traversal function
Create a function called inorder that takes a Node* called root. If root is not null, recursively call inorder on root->left, then print root->data followed by a space, then recursively call inorder on root->right.
DSA C++
Hint

Use recursion to print left subtree, current node, then right subtree.

4
Mirror the tree and print inorder traversal
In main, call mirror(root) to mirror the tree, then call inorder(root) to print the mirrored tree nodes in inorder traversal.
DSA C++
Hint

Call mirror(root) first, then inorder(root) to print the mirrored tree.