LeetCode-in-All

101. Symmetric Tree

Easy

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

Constraints:

Follow up: Could you solve it both recursively and iteratively?

Solution

#include <stdio.h>
#include <stdbool.h>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
// Helper function to check if two subtrees are mirror images
bool helper(struct TreeNode* leftNode, struct TreeNode* rightNode) {
    if (leftNode == NULL || rightNode == NULL) {
        return leftNode == NULL && rightNode == NULL;
    }
    if (leftNode->val != rightNode->val) {
        return false;
    }
    return helper(leftNode->left, rightNode->right) && helper(leftNode->right, rightNode->left);
}

// Main function to check if the tree is symmetric
bool isSymmetric(struct TreeNode* root) {
    if (root == NULL) {
        return true;
    }
    return helper(root->left, root->right);
}