0
0
DSA Typescriptprogramming~30 mins

Mirror a Binary Tree in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Mirror a Binary Tree
📖 Scenario: You are working with a binary tree data structure that represents a family tree. Sometimes, you want to see the family tree flipped like looking in a mirror, where left and right children swap places at every level.
🎯 Goal: Build a program that creates a binary tree, then writes a function to mirror it by swapping left and right children of every node. Finally, print the mirrored tree in a readable format.
📋 What You'll Learn
Create a binary tree using a TreeNode class with val, left, and right properties
Create a function mirrorTree that takes the root of the tree and swaps left and right children recursively
Print the tree nodes in pre-order traversal after mirroring
💡 Why This Matters
🌍 Real World
Mirroring trees is useful in image processing, graphical transformations, and reversing hierarchical data views.
💼 Career
Understanding tree manipulation and recursion is essential for software engineering roles involving data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with a constructor that takes a number val and initializes left and right as null. Then create a binary tree with root node value 1, left child 2, and right child 3. Assign the root node to a variable called root.
DSA Typescript
Hint

Define the TreeNode class first. Then create root and assign its left and right children.

2
Add the Mirror Function
Create a function called mirrorTree that takes a parameter node of type TreeNode | null. If node is null, return null. Otherwise, swap the left and right children of node by calling mirrorTree recursively on both children. Return the node after swapping.
DSA Typescript
Hint

Use recursion to swap left and right children. Remember to return the node after swapping.

3
Apply the Mirror Function to the Tree
Call the mirrorTree function with the variable root and assign the result back to root.
DSA Typescript
Hint

Assign the result of mirrorTree(root) back to root.

4
Print the Mirrored Tree in Pre-order
Create a function called printPreOrder that takes a node of type TreeNode | null. If node is null, return. Otherwise, print the val of node followed by a space, then recursively call printPreOrder on node.left and node.right. Finally, call printPreOrder with root.
DSA Typescript
Hint

Print the node value first, then left subtree, then right subtree. Use process.stdout.write to print on the same line with spaces.