BFS()方法进行题解。
C++ 代码
/**
* 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:
int f,len;
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return bfs(root);
}
bool bfs(TreeNode* root)
{
queue<TreeNode*> q;
q.push(root);
while(q.size())
{
len=q.size();
if(f==1)
{
if(len%2) return false;
}
int v[len*2]={0};
for(int i=0;i<len;i++)
{
auto t = q.front();
q.pop();
if(t->left)
{
q.push(t->left);
v[i*2]=t->left->val;
}
if(t->right)
{
q.push(t->right);
v[i*2+1]=t->right->val;
}
}
for(int i=0;i<len*2;i++)
{
if(v[i]!=v[2*len-1-i]) return false;
}
f=1;
}
return true;
}
};