1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool isSymmetric(TreeNode *leftNode, TreeNode *rightNode) {
    // both are NULL
    if (leftNode == NULL && rightNode == NULL) return true;

    // one and only one is NULL
    if (leftNode == NULL) return false;
    if (rightNode == NULL) return false;

    // neither is NULL, but value is different
    if (leftNode->val != rightNode->val) return false;

    // travel deeper to check
    if (!isSymmetric(leftNode->left, rightNode->right)) return false;
    return isSymmetric(leftNode->right, rightNode->left);
}

bool isSymmetric(TreeNode *root) {
    if (root == NULL) return true;
    
    return isSymmetric(root->left, root->right);
}
View Program Text


Test Status