Symmetric Tree
1,题目要求
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:
But the following [1,2,2,null,3,null,3] is not:
2,题目思路
对于这道题,目的是判断一棵树是否是镜像的,即是否是轴对称的。
如果一棵树是空的,那么它一定是对称的。
对于一颗正常的树而言,我们可以利用两个队列,依次存储左子树和右子树的节点,只不过存储的顺序有区别:
- 左子树按照“左、右”的顺序加入到队列1;
- 右子树按照“右、左”的顺序加入到队列2;
于是,类似于分别在两棵子树上做层次遍历,并依次比较节点即可。
总之,
- 层次遍历,用队列实现。
3,代码实现
/**
* 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*> q1;
queue<TreeNode*> q2;
q1.push(root->left);
q2.push(root->right);
while(!q1.empty() && !q2.empty())
{
TreeNode *leftNode = q1.front();
q1.pop();
TreeNode *rightNode = q2.front();
q2.pop();
if(leftNode == NULL && rightNode == NULL)
continue;
else if(leftNode == NULL || rightNode == NULL)
return false;
else if(leftNode->val != rightNode->val)
return false;
else if(leftNode->val == rightNode->val)
{
q1.push(leftNode->left);
q1.push(leftNode->right);
q2.push(rightNode->right);
q2.push(rightNode->left);
}
}
return true;
}
};