对称的二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路
- 递归的思路
- 递归停止的条件,走到叶子节点的子节点,如果传入的两个节点都为空,证明此时是对称的
- 如果这个节点的左孩子不等于右孩子 || 右孩子不等于左孩子 就不可能是对称的
/*
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)
{
int flag = helper(pRoot, pRoot);
return flag;
}
bool helper(TreeNode* pRoot1, TreeNode* pRoot2){
if(pRoot1 == NULL && pRoot2 == NULL){
return true;
}
if((pRoot1 != NULL && pRoot2 == NULL) || (pRoot1 == NULL && pRoot2 != NULL)){
return false;
}
if(pRoot1 -> val != pRoot2 -> val){
return false;
}
return helper(pRoot1 -> left, pRoot2 -> right) && helper(pRoot1 -> right, pRoot2 -> left);
}
};