मुख्य कंटेंट तक स्किप करें

Symmetric Tree

KANISHKA GUPTA
EditReport

Symmetric Tree

Problem Description

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

A binary tree is symmetric if the left subtree is a mirror reflection of the right subtree.

Video Explanation

Approach

To determine if a binary tree is symmetric, we can use a recursive approach. We will compare the left and right subtrees of the tree.

Steps:

  1. Checker Function: Create a helper function that takes two nodes as arguments and checks if they are mirrors of each other.

    • If both nodes are null, return true.
    • If one node is null and the other is not, return false.
    • If the values of both nodes are different, return false.
    • Recursively check the left child of the first node against the right child of the second node, and the right child of the first node against the left child of the second node.
  2. Main Function: In the main function, call the checker function with the left and right children of the root.

Solutions

class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return isMirror(root->left, root->right);
}

bool isMirror(TreeNode* t1, TreeNode* t2) {
if (!t1 && !t2) return true;
if (!t1 || !t2) return false;
return (t1->val == t2->val) && isMirror(t1->right, t2->left) && isMirror(t1->left, t2->right);
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Symmetric Tree"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.