101. Symmetric Tree. 递归判断镜像二叉树

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
101. Symmetric Tree. 递归判断镜像二叉树_第1张图片

But the following [1,2,2,null,3,null,3] is not:
101. Symmetric Tree. 递归判断镜像二叉树_第2张图片

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree

1.思路
递归求解
求一棵树是否为镜像叔 转化为 求两棵树是否镜像
对两棵树而言,考虑三种情况
(1)两颗都为空,则为镜像
(2)两颗树中有一个为空且另一个非空,则不为镜像
(3)若两颗树都不为空,则考虑 若树1左子树=树2右子树 且 树1右子树=树2左子树 ,则为镜像。

class Solution {
public:

    bool check(TreeNode* q,TreeNode* p){
        if ( !q && !p) return true;
        if ( !q || !p) return false;

        return p->val == q->val && check(q->left,p->right) && check(q->right,p->left);
    }
    bool isSymmetric(TreeNode* root) {

        return check( root, root);
    }
};

你可能感兴趣的:(101. Symmetric Tree. 递归判断镜像二叉树)