[LeetCode]101. Symmetric Tree

101. Symmetric Tree

题意:判断是否是镜像树,也就是结点的最左子树是否和最右子树是否是相等的。

DFS

思路:如果想比较结点的最左子树和最右子树,那么这就是后序遍历,也就是左右中的顺序。

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def helper(left, right):
            if not left and not right:
                return True
            elif not left or not right:
                return False
            return helper(left.left, right.right) and helper(left.right, right.left) and left.val == right.val
        if not root:
            return True
        return helper(root.left, root.right)

或者是,一样的。

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def myfunc(n1,n2):
            if n1 is None and n2 is None:
                return True
            if n1 and n2 and n1.val == n2.val:
                return myfunc(n1.left,n2.right) and myfunc(n1.right,n2.left)
            return False
        return myfunc(root, root)
posted @ 2017-08-30 13:08  banananana  阅读(102)  评论(0编辑  收藏  举报