题目:
给定一个二叉树,检查它是否是镜像对称的。
方法一:普通解法:递归
函数代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
{
return true;
}
return help(root->left,root->right);
}
bool help(TreeNode *left,TreeNode *right)
{
if(!left&&!right)
{
return true;
}
else if(!left||!right)
{
return false;
}
if(left->val!=right->val)
{
return false;
}
if(left->val==right->val)
{
return help(left->left,right->right)&&help(left->right,right->left);
}
return false;
}
};
解法二:推荐
函数代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
{
return true;
}
return help(root,root);
}
bool help(TreeNode *p,TreeNode *q)
{
if(!p&&!q)
{
return true;
}
else if(!p||!q)
{
return false;
}
return p->val==q->val&&help(p->left,q->right)&&help(p->right,q->left);
}
};