迭代
不容易想到
class Solution {
public:
bool check(TreeNode* q1,TreeNode* q2){
if(!q1&&!q2)return 1;
if(!q1||!q2)return 0;
return q1->val==q2->val&&check(q1->left,q2->right)&&check(q1->right,q2->left);
}
bool isSymmetric(TreeNode* root) {
return check(root,root);
}
};
广度搜索(两个数组记录)
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)return 1;
vector<TreeNode*>temp1;
vector<TreeNode*>temp2;
temp1.push_back(root);
while(!temp1.empty()||!temp2.empty()){
if(!temp1.empty()){
int n=temp1.size();
for(int i=0;i<n;i++){
if(temp1[i]==NULL&&temp1[n-1-i]!=NULL)return 0;
if(temp1[i]!=NULL&&temp1[n-1-i]==NULL)return 0;
if(temp1[i]!=NULL&&temp1[n-1-i]!=NULL){
if(temp1[i]->val!=temp1[n-1-i]->val)return 0;
temp2.push_back(temp1[i]->left);
temp2.push_back(temp1[i]->right);
}
}
temp1.clear();
}else{
int n=temp2.size();
for(int i=0;i<n;i++){
if(temp2[i]==NULL&&temp2[n-1-i]!=NULL)return 0;
if(temp2[i]!=NULL&&temp2[n-1-i]==NULL)return 0;
if(temp2[i]!=NULL&&temp2[n-1-i]!=NULL){
if(temp2[i]->val!=temp2[n-1-i]->val)return 0;
temp1.push_back(temp2[i]->left);
temp1.push_back(temp2[i]->right);
}
}
temp2.clear();
}
}
return 1;
}
};
广度搜索(一个队列记录)
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)return 1;
queue<TreeNode*>temp1;
temp1.push(root);
temp1.push(root);
while(!temp1.empty()){
int n=temp1.size();
for(int i=0;i<n;i=i+2){
auto q1=temp1.front();
temp1.pop();
auto q2=temp1.front();
temp1.pop();
if(!q1&&!q2)continue;
if(!q1||!q2)return 0;
if(q1->val!=q2->val)return 0;
temp1.push(q1->left);
temp1.push(q2->right);
temp1.push(q1->right);
temp1.push(q2->left);
}
}
return 1;
}
};