leetcode(34)-----对称二叉树

版权声明:本文为博主原创文章,未经允许不得转载。 https://blog.csdn.net/wem603947175/article/details/81989089

101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。


Python代码实现:

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def issametree(l, r):
            if not l and not r:
                return True
            if l and r and l.val == r.val:
                return issametree(l.left, r.right) and issametree(r.left, l.right)
            else:
                return False
        if not root:
            return True
        return issametree(root.left, root.right)

自己的,我觉得没毛病,但是仍报错。。。。。。

# 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 isSametric(self,p,q):
        if q == None and p == None:
            return True
        if q and p and q.val == p.val:
            l = self.isSametric(p.left, q.left)
            k = self.isSametric(p.right, q.right)
            return l and k
        else:
            return False
    def isSymmetric(self, root):
        return self.isSametric(root.left,root.right)

猜你喜欢

转载自blog.csdn.net/wem603947175/article/details/81989089