Skip to main content

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 NULL and the other is not, it's asymmetric.
    • Otherwise, check:
      • values of left->val == right->val
      • left->left vs right->right
      • left->right vs right->left

🧩 Key Concept​

We recursively compare:

  • Outer pair: left.left vs right.right
  • Inner pair: left.right vs right.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​

MetricValue
TimeO(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​

ApproachDescription
Iterative BFSUse a queue and push mirror pairs
DFS RecursionClean and intuitive (used here)


πŸ’¬

Discussion & Doubts