0
0
DSA Javascriptprogramming~30 mins

Mirror a Binary Tree in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Mirror a Binary Tree
📖 Scenario: Imagine you have a family tree represented as a binary tree. You want to create a mirror image of this tree, flipping it left to right, like looking at it in a mirror.
🎯 Goal: You will build a program that creates a mirror of a given binary tree by swapping the left and right children of every node.
📋 What You'll Learn
Create a binary tree node class called TreeNode with value, left, and right properties
Create a sample binary tree with exact nodes and structure
Write a function called mirrorTree that mirrors the binary tree by swapping left and right children recursively
Print the tree nodes in level order after mirroring to show the mirrored structure
💡 Why This Matters
🌍 Real World
Mirroring binary trees is useful in graphics, image processing, and reversing hierarchical data structures.
💼 Career
Understanding tree manipulations like mirroring helps in coding interviews and software roles involving data structures.
Progress0 / 4 steps
1
Create the Binary Tree Node Class and Sample Tree
Create a class called TreeNode with a constructor that takes value and sets left and right to null. Then create the following tree structure by creating nodes and linking them:
1
/ \
2 3
/ \ \
4 5 6
DSA Javascript
Hint

Define the TreeNode class first. Then create the root node with value 1. Add left and right children as shown in the tree diagram.

2
Create a Helper Function to Print the Tree in Level Order
Create a function called printLevelOrder that takes the root node and prints the values of the tree nodes level by level separated by spaces. Use a queue to traverse the tree breadth-first.
DSA Javascript
Hint

Use a queue array starting with the root. Remove the first node, print its value, then add its children to the queue. Repeat until queue is empty.

3
Write the Mirror Function to Swap Left and Right Children
Write a function called mirrorTree that takes a node and swaps its left and right children recursively for the entire tree.
DSA Javascript
Hint

Swap the left and right children of the current node. Then call mirrorTree recursively on the left and right children.

4
Print the Mirrored Tree
Call mirrorTree with the root node, then call printLevelOrder with the root node to print the mirrored tree nodes in level order.
DSA Javascript
Hint

Call mirrorTree(root) to mirror the tree, then printLevelOrder(root) to print the mirrored tree nodes.