/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//两边进行遍历,一边左右中,一边右左中,分成两部分的遍历
bool cmp(TreeNode* left, TreeNode* right){
if (left == NULL && right == NULL) return true;
else if (left != NULL && right == NULL) return false;
else if (left == NULL && right != NULL) return false;
else if (left->val != right->val) return false;
// 左右节点都不为空,且数值相同的情况
//比较外侧,比较内侧
bool out = cmp(left->left, right->right); // 左子树:左、 右子树:右
bool in = cmp(left->right, right->left); // 左子树:右、 右子树:左
bool isSame = out && in; // 左子树:中、 右子树:中(逻辑处理)
return isSame;
}
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
return cmp(root->left, root->right);
}
};