AlgoMaster Logo

Symmetric Tree

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The symmetric tree problem can be solved by recursively checking if the left subtree is a mirror of the right subtree. More formally, two trees are a mirror of each other if:

  1. Their two roots have the same value.
  2. The right subtree of each tree is a mirror of the left subtree of the other tree.

Intuition:

  • A tree is symmetric if the left subtree is a mirror reflection of the right subtree.
  • For each node, compare the left and right subtrees for mirror-like properties.
  • This can be implemented using a recursive function that checks these properties at every node.

Steps:

  1. If both nodes are null, they are symmetric.
  2. If only one of the nodes is null, they are not symmetric.
  3. Check if the current nodes have the same value.
  4. Recursively check the left and right children.

Code:

2. Iterative Approach using Queue

Another way to solve the symmetric tree problem is by using an iterative approach with a queue. The idea is similar to the recursive approach, but we employ a queue to imitate the function call stack.

Intuition:

  • Instead of recursion, maintain a queue to process nodes in layers.
  • Enqueue pairs of nodes to be compared.
  • If at any point, the nodes are not symmetric, return false.

Steps:

  1. Use a queue to store nodes for comparison.
  2. Initially, enqueue the left and right child of the root.
  3. While the queue is not empty, extract a pair of nodes.
  4. If both are null, continue the loop.
  5. If one is null, return false.
  6. If their values differ, return false.
  7. Enqueue the children of the nodes in the order to maintain the symmetry.

Code: