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,#,3,#,3}
is not:
1
/ \
2 2
\ \
3 3
解题思路1:
递归。判断是否对称,可以先将其中一子树翻转(类似于Lintcode 175. 翻转二叉树),然后看两子树是否相等(类似于Lintcode 469. Same Tree)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: root of the given tree
* @return: whether it is a mirror of itself
*/
bool isSymmetric(TreeNode * root)
{
// Write your code here
if(root == NULL)
return true;
TreeNode * left = root->left;
TreeNode * right = root->right;
right = revert(right);
return is_identical(left,right);
}
TreeNode * revert(TreeNode * root)
{
if(root == NULL)
return NULL;
revert(root->left);
revert(root->right);
swap(root->left , root->right);
return root;
}
bool is_identical(TreeNode * root1 , TreeNode * root2)
{
if(root1 == NULL && root2 == NULL)
return true;
else if(root1 != NULL && root2 == NULL)
return false;
else if(root1 == NULL && root2 != NULL)
return false;
else
{
if(root1->val != root2->val)
return false;
else
return is_identical(root1->left,root2->left) && is_identical(root1->right,root2->right);
}
}
};
解题思路2:
循环,使用辅助数据结构--队列。类似于广度优先遍历。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: root of the given tree
* @return: whether it is a mirror of itself
*/
bool isSymmetric(TreeNode * root)
{
// Write your code here
if(root == NULL)
return true;
queue<TreeNode *> q1;
queue<TreeNode *> q2;
q1.push(root);
q2.push(root);
while(!q1.empty() && !q2.empty())
{
TreeNode * node1 = q1.front();
q1.pop();
TreeNode * node2 = q2.front();
q2.pop();
if(node1 == NULL && node2 == NULL)
continue;
if(node1 == NULL || node2 == NULL)//若一个为空,一个不为空,则false
return false;
if(node1->val != node2->val)
return false;
q1.push(node1->left);
q1.push(node1->right);
q2.push(node2->right);
q2.push(node2->left);
}
return q1.empty() && q2.empty();
}