题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:用层次遍历,每层都判断一下是否是对称的,如果有一层不是对称的,则返回false,否则返回true。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool levelTraverse(TreeNode *root)
{
queue<TreeNode *> q;
q.push(root);
int k=1,level=1;//level表示当前层中的节点数
while(!q.empty())
{
vector<int> result;
k=level;
level=0;
for(int i=0;i<k;i++)
{
if(q.front()->left==NULL)
result.push_back(INT_MIN);
else
{
result.push_back(q.front()->left->val);
q.push(q.front()->left);
level++;
}
if(q.front()->right==NULL)
result.push_back(INT_MIN);
else
{
result.push_back(q.front()->right->val);
q.push(q.front()->right);
level++;
}
q.pop();
}
for(int i=0;i<(result.size()>>1);i++)
if(result[i]!=result[result.size()-1-i])
return false;
}
return true;
}
bool isSymmetric(TreeNode *root)
{
if(root==NULL)
return true;
levelTraverse(root);
}
int main()
{
TreeNode* root=new TreeNode(1);
root->left=new TreeNode(1);
root->right=new TreeNode(1);
root->left->left=new TreeNode(1);
root->right->left=new TreeNode(1);
cout<<isSymmetric(root)<<endl;
system("pause");
return 0;
}