0
0
DSA Goprogramming~30 mins

Mirror a Binary Tree in DSA Go - Build from Scratch

Choose your learning style9 modes available
Mirror a Binary Tree
📖 Scenario: You are working on a simple program that deals with binary trees. A binary tree is like a family tree where each person has up to two children: a left child and a right child.Sometimes, you want to flip this tree so that the left and right children of every node swap places. This is called mirroring the tree.
🎯 Goal: Build a Go program that creates a binary tree, then mirrors it by swapping left and right children at every node, and finally prints the mirrored tree in a simple format.
📋 What You'll Learn
Create a binary tree node struct with integer values and left/right pointers
Build a specific binary tree with given values
Write a function to mirror the binary tree by swapping left and right children recursively
Print the tree nodes in preorder traversal after mirroring
💡 Why This Matters
🌍 Real World
Mirroring trees is useful in graphics, image processing, and data structure transformations.
💼 Career
Understanding tree manipulations and recursion is essential for software engineering roles involving data structures and algorithms.
Progress0 / 4 steps
1
Create the binary tree structure and build the tree
Define a struct called Node with fields Val int, Left *Node, and Right *Node. Then create a variable root that builds this exact tree:

1
/ \\
2 3
/ / \\
4 5 6

Use &Node{Val: value, Left: ..., Right: ...} syntax to build the tree.
DSA Go
Hint

Start by defining the Node struct with the three fields. Then build the tree from the bottom up using nested &Node{} expressions.

2
Add a helper function to mirror the tree
Create a function called mirror that takes a pointer to Node named root. This function should swap the Left and Right children of root and then call itself recursively on both children if they are not nil.
DSA Go
Hint

Check if root is nil. If not, swap Left and Right. Then call mirror recursively on both children.

3
Call the mirror function on the tree
In the main function, call the mirror function with the root node to mirror the entire tree.
DSA Go
Hint

Simply call mirror(root) inside main after building the tree.

4
Print the mirrored tree in preorder traversal
Create a function called printPreorder that takes a pointer to Node named root. It should print the Val of each node in preorder (root, left, right) separated by spaces. Then call printPreorder(root) in main after mirroring the tree.
DSA Go
Hint

Print the current node's value, then recursively print the left subtree, then the right subtree. Call this function after mirroring.