leetcode 101. Symmetric Tree

来源:互联网 发布:衢州学院网络课程 编辑:程序博客网 时间:2024/06/07 22:49

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:
1
/ \
2 2
/ \ / \
3 4 4 3
思路:对称树的结构是递归的,我们也用递归去遍历节点。因为根节点与其他节点有些不同,所以需要再定义一个函数去遍历节点,而初始给的函数来作为开始。初始只需要判断根节点是否为空,是就return True,否就调用我们定义的函数。然后每次都先判断是否都为空?是否一空一不空?都不空的话值是否相等,若是相等,就要用inpair去遍历整个树结构中靠中间的部分,outpair去遍历整个树结构中靠两边的部分,再返回判断出的布尔值;若不等就直接返回False了。这样最后返回的就是一串布尔值的and运算。

class Solution(object):    def isSymmetric(self, root):        """        :type root: TreeNode        :rtype: bool        """        if root == None:            return True        else:            return self.isMirror(root.left, root.right)    def isMirror(self, left, right):        if left == None and right == None:            return True        if left == None or right == None:            return False        if left.val == right.val:            inpair = self.isMirror(left.right, right.left)            outpair = self.isMirror(left.left, right.right)            return inpair and outpair        else:            return False
原创粉丝点击