Question:
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 not:
1
/ \
2 2
\ \
3 3
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
* 使用队列,宽度优先遍历。定义结构体MP,来记录节点的唯一位置
*/
class Solution {
public:
typedef struct MP{
TreeNode* node;//节点
pair<int,int> f;//父节点和当前节点
int d;//左孩子还是右孩子标志,对于根节点的左孩子的子孙几点,0代表左,1代表右;根节点的右孩子的子孙节点与根的左孩子相反
MP(TreeNode* n , pair<int,int> p,int dd):node(n),f(p),d(dd){}
}MP;
bool isSymmetric(TreeNode* root) {
if(!root || !root->left&&!root->right){
return true;
}
vector<MP*> p1;
vector<MP*> p2;
//根节点左右孩子入队列
if(root->left){
p1.push_back(new MP(root->left,make_pair(root->val,root->left->val),0));
}
if(root->right){
p2.push_back(new MP(root->right,make_pair(root->val,root->right->val),0));
}
//左右孩子按广度优先入队列
for(int i = 0 ; i<p1.size();i++){
if(p1[i]->node->left){
p1.push_back(new MP(p1[i]->node->left,make_pair(p1[i]->node->val,p1[i]->node->left->val),0));
}
if(p1[i]->node->right){
p1.push_back(new MP(p1[i]->node->right,make_pair(p1[i]->node->val,p1[i]->node->right->val),1));
}
}
for(int i = 0 ; i<p2.size();i++){
if(p2[i]->node->right){
p2.push_back(new MP(p2[i]->node->right,make_pair(p2[i]->node->val,p2[i]->node->right->val),0));
}
if(p2[i]->node->left){
p2.push_back(new MP(p2[i]->node->left,make_pair(p2[i]->node->val,p2[i]->node->left->val),1));
}
}
//检测两个队列是否相等
int len;
if((len=p1.size())!=p2.size()){
return false;
}
for(int i = 0;i<len;i++){
if(p1[i]->f == p2[i]->f && p1[i]->d == p2[i]->d){
continue;
}
else{
return false;
}
}
return true;
}
};
总结:
父节点是必须要给出的,比如
用例:2,3,3,4,5,5,4,null,null,8,9,null,null,9,8.
如果不给出父节点,结果出错。