Symmetric Tree
TreesDFS / BFS
Problem Statement
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Solution 1: Recursive
The recursive approach checks for symmetry by comparing the left and right subtrees in a mirrored fashion.
Algorithm Steps
- Create a helper function that takes two nodes as arguments.
- If both nodes are null, they are symmetric.
- If one node is null or their values are not equal, they are not symmetric.
- Recursively call the helper function, comparing the left child of the first node with the right child of the second node, and vice versa.
Symmetric: true
Comparing left node 2 and right node 2.
Symmetric Tree Solution
Solution 2: Iterative
The iterative approach uses a queue to compare the left and right subtrees level by level.
Algorithm Steps
- Create a queue and add the left and right children of the root.
- While the queue is not empty, dequeue two nodes.
- If both nodes are null, continue.
- If one node is null or their values are not equal, they are not symmetric.
- Enqueue the children of the two nodes in a mirrored fashion.
Symmetric: true
Comparing left node 2 and right node 2.
Symmetric Tree Solution