Fork me on GitHub

Symmetric Tree

Description

https://leetcode.com/problems/symmetric-tree/description/

Solution

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
TreeNode* left = root->left;
TreeNode* right = root->right;

return check(left, right);
}

bool check(TreeNode* l, TreeNode* r) {
if (l == NULL && r == NULL) return true;
if (l == NULL || r == NULL) return false;
if (l->val != r->val) return false;

return this->check(l->left, r->right) && this->check(l->right, r->left);
}
};