0
0
DSA Typescriptprogramming~30 mins

Check if Two Trees are Symmetric in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Check if Two Trees are Symmetric
📖 Scenario: Imagine you have two family trees represented as binary trees. You want to check if these two trees are mirror images of each other, meaning they are symmetric around their center.
🎯 Goal: Build a TypeScript program that creates two binary trees, sets a helper variable, writes a function to check if the two trees are symmetric, and finally prints the result.
📋 What You'll Learn
Create two binary trees using the TreeNode class with exact values
Create a helper variable called result initialized to true
Write a function called isSymmetric that takes two TreeNode parameters and returns a boolean
Use recursion inside isSymmetric to check if the trees are symmetric
Print the final result which is true if symmetric, otherwise false
💡 Why This Matters
🌍 Real World
Checking if two trees are symmetric is useful in graphics, data organization, and comparing hierarchical data structures.
💼 Career
Understanding tree symmetry helps in coding interviews and software roles involving data structures and algorithms.
Progress0 / 4 steps
1
Create two binary trees
Create a class called TreeNode with val, left, and right properties. Then create two trees called tree1 and tree2 with these exact nodes:

tree1: root value 1, left child 2, right child 3
tree2: root value 1, left child 3, right child 2
DSA Typescript
Hint

Define the TreeNode class first. Then create tree1 with root 1, left 2, right 3. Create tree2 with root 1, left 3, right 2.

2
Add a helper variable
Create a boolean variable called result and set it to true. This will store if the trees are symmetric or not.
DSA Typescript
Hint

Just write let result = true; below the tree creation.

3
Write the symmetric check function
Write a function called isSymmetric that takes two parameters node1 and node2 of type TreeNode | null. Use recursion to check if the two trees are mirror images. Return true if symmetric, otherwise false. Use these rules:
- If both nodes are null, return true
- If one is null and the other is not, return false
- If values differ, return false
- Recursively check node1.left with node2.right and node1.right with node2.left
DSA Typescript
Hint

Use the rules given to write the recursive function. Then assign result by calling isSymmetric(tree1, tree2).

4
Print the result
Print the value of the variable result to show if the two trees are symmetric or not.
DSA Typescript
Hint

Use console.log(result); to print the final answer.