问题描述:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
代码描述:
思路:参考按层遍历,需要一个额外的vector存储每一层,每压入一层数据,就进行一次判断,不满足直接退出。满足的话,清空,继续存储下一行。需要额外处理的是空的情况。时间复杂度O(n),空间复杂度O(n)。以下代码采用迭代实现。
/**
* 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:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
queue<TreeNode*> q;
q.push(root);
vector<int> temp;
temp.push_back(root->val);
int count = 0;
TreeNode* n;
while(!q.empty())
{
count = q.size();
temp.clear();
while(count > 0)
{
n = q.front();
q.pop();
if(n->left != NULL)
{
q.push(n->left);
temp.push_back(n->left->val);
}
else
temp.push_back(-1);
if(n->right != NULL)
{
q.push(n->right);
temp.push_back(n->right->val);
}
else
temp.push_back(-1);
--count;
}
if(temp.size() == 0) break;
int longth = (temp.size() - 1);
int start = 0;
while(start < longth)
{
if(temp[start] != temp[longth])
return false;
--longth;
++start;
}
}
return true;
}
};