【剑指Offer】对称的二叉树(递归)

题目链接

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路:判断二叉树是否对称,也就是比较左右子树是否对称,那么递归比较左右子树即可。

代码:

/*
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 isSymmetrical(pRoot,pRoot);
    }

    bool isSymmetrical(TreeNode* pRoot1,TreeNode* pRoot2) {
        if(pRoot1 == nullptr && pRoot2 == nullptr) {
            return true;
        }
        if(pRoot1 == nullptr || pRoot2 == nullptr || pRoot1 -> val != pRoot2 -> val) {
            return false;
        }
        return isSymmetrical(pRoot1->left,pRoot2->right) && isSymmetrical(pRoot2->right,pRoot1->left);
    }

};

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/80876850