0
0
DSA Javascriptprogramming~3 mins

Why Check if Two Trees are Symmetric in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

Discover how a simple trick can save you hours of confusing tree comparisons!

The Scenario

Imagine you have two family trees drawn on paper, and you want to see if they are mirror images of each other. Doing this by looking at every branch and comparing each node manually can be confusing and tiring.

The Problem

Manually checking each branch and node is slow and easy to mess up. You might forget to compare some parts or mix up the order, leading to wrong conclusions about whether the trees are symmetric.

The Solution

Using a simple step-by-step method, we can automatically compare the trees by checking if the left side of one tree matches the right side of the other, and vice versa. This makes the process fast, clear, and error-free.

Before vs After
Before
function areSymmetric(t1, t2) {
  // Manually compare nodes one by one
  if (!t1 && !t2) return true;
  if (!t1 || !t2) return false;
  if (t1.val !== t2.val) return false;
  return areSymmetric(t1.left, t2.right) && areSymmetric(t1.right, t2.left);
}
After
function isSymmetric(root) {
  function check(t1, t2) {
    if (!t1 && !t2) return true;
    if (!t1 || !t2) return false;
    if (t1.val !== t2.val) return false;
    return check(t1.left, t2.right) && check(t1.right, t2.left);
  }
  return check(root.left, root.right);
}
What It Enables

This lets us quickly and reliably tell if two trees are mirror images, which helps in many computer tasks like organizing data or checking structures.

Real Life Example

Think of checking if two family trees are mirror images to find if two families have symmetrical relationships or patterns, without drawing and comparing every branch by hand.

Key Takeaways

Manual comparison of trees is slow and error-prone.

Recursive checking of left and right nodes simplifies the process.

Automated symmetry checks save time and avoid mistakes.