递归版
class Solution {
private:
bool symmetric(TreeNode* left,TreeNode* right){
if(!left&&!right) return true;
else if(left&&!right || !left&&right) return false;
else{
if(left->val == right->val) return symmetric(left->left,right->right)&&symmetric(left->right,right->left);
else return false;
}
}
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
else return symmetric(root->left,root->right);
}
};
非递归版
class Solution {
public:
bool isSymmetric(TreeNode* root) {
queue<TreeNode *> que;
vector<vector<int>> vec;
if (!root) return true;
que.push(root);
while(que.size() != 0){
vector<int> tmpVec;
queue<TreeNode*> tmpQue;
while(que.size() != 0){
TreeNode * node = que.front();
que.pop();
if(node->left) tmpQue.push(node->left);
else if(!node->left && node->val != -100) tmpQue.push(new TreeNode(-100));
if(node->right) tmpQue.push(node->right);
else if(!node->right && node->val != -100) tmpQue.push(new TreeNode(-100));
tmpVec.push_back(node->val);
}
vec.push_back(tmpVec);
que = tmpQue;
}
for (int i = 1;i<vec.size();i++){
vector<int> tmp = vec[i];
if(tmp.size()%2 != 0) return false;
for(int j = 0;j<tmp.size();j++){
if(tmp[j] == tmp[tmp.size()-j-1]) continue;
else return false;
}
}
return true;
}
};
这个非递归版是可以骗过机器,但是可能会出问题,选择的值应该是不会出现的值才行。而且效率也不高。。。