我的题解:
1.层次遍历真的太容易实现了,每次都先想到层次
一次读取两个结点
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
queue<TreeNode*> q;
TreeNode* a;
TreeNode* b;
q.push(root->left);
q.push(root->right);
while(!q.empty()){
a=q.front();
q.pop();
b=q.front();
q.pop();
if(!a && !b) continue;
if((a &&!b)||(b&& !a)||(a->val!=b->val)) return false;
q.push(a->left);
q.push(b->right);
q.push(a->right);
q.push(b->left);
}
return true;
}
};
2.递归
其实这两种方法就相当于BFS和DFS
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return dfs(root->left,root->right);
}
bool dfs(TreeNode* a,TreeNode* b){
if(!a && !b) return true;
if((!a&&b)||(a&&!b)||(a->val!=b->val)) return false;
return dfs(a->left,b->right)&&dfs(a->right,b->left);
}
};