Symmetric Binary Tree
Problem Statement:β
Given theΒ rootΒ of a binary tree,Β check whether it is a mirror of itselfΒ (i.e., symmetric around its center).
Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false
-
Example:
β Solution: Recursion (Mirror Tree Comparison)β
class Solution {
public:
// Helper function to compare two subtrees
bool isMirror(TreeNode *t1, TreeNode *t2){
if(t1 == NULL && t2 == NULL) return true;
if(t1 == NULL || t2 == NULL) return false;
return (t1->val == t2->val &&
isMirror(t1->left, t2->right) &&
isMirror(t1->right, t2->left));
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return isMirror(root->left, root->right);
}
};
π How It Worksβ
- A binary tree is symmetric if the left and right subtrees are mirror images.
- The helper function
isMirror(left, right)checks:- If both nodes are
NULL, they are symmetric at that level. - If one is
NULLand the other is not, it's asymmetric. - Otherwise, check:
- values of
left->val == right->val left->leftvsright->rightleft->rightvsright->left
- values of
- If both nodes are
π§© Key Conceptβ
We recursively compare:
- Outer pair:
left.leftvsright.right - Inner pair:
left.rightvsright.left
The recurrence:
isSymmetric(root) = isMirror(root->left, root->right)
isMirror(t1, t2) =
t1 == NULL && t2 == NULL β true
t1 == NULL || t2 == NULL β false
t1->val == t2->val &&
isMirror(t1->left, t2->right) &&
isMirror(t1->right, t2->left)
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(N) |
| Space (stack) | O(H), H=height of tree (worst O(N) for skewed) |
β οΈ Edge Casesβ
- Empty tree β symmetric
- Only root β symmetric
- One child missing in left/right β not symmetric
π‘ Other Approachesβ
| Approach | Description |
|---|---|
| Iterative BFS | Use a queue and push mirror pairs |
| DFS Recursion | Clean and intuitive (used here) |
π Related Problemsβ
- Leetcode 101. Symmetric Tree
- Leetcode 100. Same Tree
- [Check if Tree is Foldable]
- [Mirror of Binary Tree]
π¬