DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on

1

LeetCode #101 Symmetric Tree with JavaScript

Solutions to LeetCode's 101. Symmetric Tree with JavaScript.

Follow up: Could you solve it both recursively and iteratively?

Solution 1: Recursive

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
const isSymmetric1 = (root) => {
  const isMirror = (left, right) => {
    if (!left && !right) return true;
    if (!left || !right) return false;
    if (left.val !== right.val) return false;
    return isMirror(left.left, right.right) && isMirror(left.right, right.left);
  };
  return isMirror(root, root);
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

Solution 2: Iterative BFS

/**
 * @param {TreeNode} root
 * @return {boolean}
 */
const isSymmetric2 = (root) => {
  const queue1 = [root.left];
  const queue2 = [root.right];

  while (queue1.length > 0 || queue2.length > 0) {
    const dequeued1 = queue1.shift();
    const dequeued2 = queue2.shift();

    if (!dequeued1 && !dequeued2) continue;
    if (!dequeued1 || !dequeued2) return false;
    if (dequeued1.val !== dequeued2.val) return false;

    queue1.push(dequeued1.left);
    queue1.push(dequeued1.right);
    queue2.push(dequeued2.right);
    queue2.push(dequeued2.left);
  }
  return true;
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)

I used BFS to solve the problem with iteration.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay