Niuke.com sword refers to offer-symmetrical binary tree

topic description

Please implement a function to judge whether a binary tree is symmetric. Note that a binary tree is defined as symmetric if it is identical to its mirror image.

/*
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 == nullptr)
            return true;
        return isSymmetrical(pRoot->left, pRoot->right);
    }
private:
    bool isSymmetrical(TreeNode* p1, TreeNode* p2)
    {
        if (p1 == nullptr && p2 == nullptr)
            return true;
        if (p1 == nullptr || p2 == nullptr)
            return false;
        if (p1->val != p2->val)
            return false;
        else
            return isSymmetrical(p1->left, p2->right) && isSymmetrical(p2->left, p1->right);
    }
};

Guess you like

Origin blog.csdn.net/yhn19951008/article/details/79434002