第一个while那行,结尾多了一个分号。
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isSymmetric(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> q;
TreeNode* p = root;
if (p == NULL)
return true;
else
q.push(p);
while (!q.empty())
{
vector<int> tmp;
int size = q.size();
for (int i = 0; i < size; i++)
{
p = q.front();
q.pop();
if (p != NULL)
tmp.push_back(p->val);
else
tmp.push_back(-1);
if (p != NULL)
{
if (p->left != NULL)
q.push(p->left);
else
q.push(NULL);
if (p->right != NULL)
q.push(p->right);
else
q.push(NULL);
}
}
ans.push_back(tmp);
}
for (int i = 0; i < ans.size(); i++)
{
for (int j = 0; j < ans[i].size() / 2; j++)
{
if (ans[i][j] != ans[i][ans[i].size() - j-1])
return false;
}
}
return true;
}
int main()
{
TreeNode t1(1);
TreeNode t2(2);
TreeNode t3(2);
TreeNode t4(3);
TreeNode t5(3);
t1.left = &t2;
t1.right = &t3;
t2.right = &t5;
t3.right = &t4;
TreeNode* t = &t1;
cout << isSymmetric(t);
return 0;
}
用的是测试上面给出的第二个案例:
测试结果:
最后代码也能通过LeetCode的oj
LeetCode通过代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode*> q;
TreeNode* p = root;
if (p == NULL)
return true;
else
q.push(p);
while (!q.empty())
{
vector<int> tmp;
int size = q.size();
for (int i = 0; i < size; i++)
{
p = q.front();
q.pop();
if (p != NULL)
tmp.push_back(p->val);
else
tmp.push_back(-1);
if (p != NULL)
{
if (p->left != NULL)
q.push(p->left);
else
q.push(NULL);
if (p->right != NULL)
q.push(p->right);
else
q.push(NULL);
}
}
ans.push_back(tmp);
}
for (int i = 0; i < ans.size(); i++)
{
for (int j = 0; j < ans[i].size() / 2; j++)
{
if (ans[i][j] != ans[i][ans[i].size() - j-1])
return false;
}
}
return true;
}
};