题解
- 递归
/**
* 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:
vector<int>res;
bool dfs(TreeNode *p,TreeNode *q){
if(p != NULL && q != NULL){
if(p->val == q->val && dfs(p->left,q->right) && dfs(p->right,q->left))return true;
}
else if(p == NULL && q == NULL)return true;
return false;
}
bool isSymmetric(TreeNode* root) {
return dfs(root,root);
}
};
- 迭代
/**
* 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:
queue<TreeNode *>q;
bool isSymmetric(TreeNode* root) {
q.push(root),q.push(root);
TreeNode *left,*right;
while(!q.empty()){
left = q.front();
q.pop();
right = q.front();
q.pop();
if(left != NULL && right == NULL || left == NULL && right != NULL)return false;
if(left != NULL && right != NULL && left->val != right->val)return false;
if(left == NULL)continue;
q.push(left->left),q.push(right->right);
q.push(left->right),q.push(right->left);
}
return true;
}
};