1. Description
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is n
1
/ \
2 2
\ \
3 3
2. Analysis
直接的想法就是取出每一层,在该层做左右对称比较。思想与逐层遍历是类似的。时间复杂度为 O(n)
3. Algorithm achievement
/**
* 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 == NULL) return true;
if(root->left == NULL && root->right == NULL) return true;
if(root->left == NULL || root->right == NULL) return false;
vector<TreeNode*> tmp;
TreeNode* node = NULL;
tmp.push_back(root);
while(!tmp.empty()) {
for(int i = 0, n = tmp.size(); i < n; i++) {
node = tmp.front();
tmp.erase(tmp.begin());
/*判断条件这里需要细心,有点坑*/
if(node != NULL) {
tmp.push_back(node->left);
tmp.push_back(node->right);
}
}
if(tmp.size()%2 != 0) return false;
for(int i = 0, j = tmp.size()-1; i < tmp.size()/2; i++, j--) {
if(tmp[i] == NULL && tmp[j] == NULL ) continue;
if(tmp[i] == NULL || tmp[j] == NULL ) return false;
if(tmp[i] != NULL && tmp[j] != NULL) {
if((tmp[i])->val != (tmp[j])->val)
return false;
} else if(tmp[i] != NULL || tmp[j] != NULL)
return false;
}
}
return true;
}
};
贴个图防坑!注意NULL结点也会参与比较的,所以需要接入向量!