Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90737952
Method One: recursive
Problem-solving ideas:
First determine whether the current root root is null, and if so, returns true;
IsSame then calls the function, it is determined whether the left and right node satisfies the requirements of symmetry;
In isSame function, the core idea is recursive compare r1-> left == r2-> right and r1-> right == r2-> left.
/**
* 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) return true;
else return isSame(root->left, root->right);
}
bool isSame(TreeNode* r1, TreeNode* r2){
if(!r1 || !r2) return r1 == r2;
else{
return (r1->val == r2->val) && isSame(r1->left, r2->right) && isSame(r1->right, r2->left);
}
}
};