请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路:对称的二叉树中左子树的左孩子等于右子树的右孩子,左子树的右孩子等于右子树的左孩子
而且当左右子树中有一个为空时就不会是对称
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if(pRoot==NULL)
return true;
else
return
isSymmetricalChild(pRoot->left,pRoot->right);//判断其孩子是不是对称
}
bool isSymmetricalChild(TreeNode* pRoot1,TreeNode* pRoot2)
{
if(pRoot1==NULL&&pRoot2==NULL)//当两个都为空时为对称
return true;
if(pRoot1==NULL||pRoot2==NULL)//当有一个为空时为假
return false;
if(pRoot1->val==pRoot2->val)
return isSymmetricalChild(pRoot1->left,pRoot2->right)&&isSymmetricalChild(pRoot1->right,pRoot2->left);//左子树的左孩子等于右子树的右孩子
return false;
}
};