题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解决方法
/*
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)
{
return isS(pRoot,pRoot);
}
bool isS(TreeNode *p,TreeNode *q){
if (!p && !q) return true; //两个树为空
else if (!p || !q) return false;//只有一个树为空
else if (p->val!=q->val) return false;
else return (isS(p->left,q->right) && isS(p->right,q->left));
}
};