[Leetcode]@python 101. Symmetric Tree

题目链接

https://leetcode.com/problems/symmetric-tree/

题目原文

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

For example, this binary tree is symmetric:

But the following is not:

题目大意

给定一棵二叉树,判断这课二叉树是否对称

解题思路

从根节点出发,当存在左右子树的时候,判断左右子树的根节点的值是否相等,如果相等则递归判断左子树的左子树根节点与右子树的右子树根节点以及左子树的右子树根节点与右子树的左子树根节点是否相等。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def symmetric(self, l, r):
        if l == None and r == None:
            return True
        if l and r and l.val == r.val:
            return self.symmetric(l.left, r.right) and self.symmetric(l.right, r.left)
        return False

    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        else:
            return self.symmetric(root.left, root.right)
原文地址:https://www.cnblogs.com/slurm/p/5239983.html