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
Note:
Bonus points if you could solve it both recursively and iteratively.
题意:给定一个二叉树,判断它是否是镜像对称的
思路:在前面用bfs遍历树的基础上做一些改动,就是开两个队列,分别存储左右两棵子树,注意两棵子树入队的顺序是相反的,然后依次比较两个队列的第一个元素。
代码:
class Solution { public: //BFS,开两个队列来存储两棵子树,注意左右两棵子树push进队列的顺序相反 //每次弹出front进行判断,都为空则继续,只有一个为空,或者值不等,则立即返回false; bool isSymmetric(TreeNode* root) { TreeNode *l,*r; queue<TreeNode *>lq,rq; if(root==NULL) return true; lq.push(root->left); rq.push(root->right); while(!lq.empty() && !rq.empty()){ l=lq.front(); r=rq.front(); lq.pop(); rq.pop(); if(!l && !r) continue; if(!l || !r) return false; if(l->val != r->val) return false; lq.push(l->left); lq.push(l->right); rq.push(r->right); rq.push(r->left); } return true; } };