剑指Offer 58. 对称的二叉树 (二叉树)

Posted on 2018-10-18 10:05  _hqc  阅读(139)  评论(0编辑  收藏  举报

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

题目地址

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb?tpId=13&tqId=11211&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

判断一棵二叉树是不是对称的,等价于判断其左右子树是不是镜像对称的。判断镜像对称即判断对称位置上的元素是不是相等的。

两个结点AB对称等价于:

两个结点值相等

结点A的左子树和结点B的右子树对称

结点A的右子树和结点B的左子树对称

Python

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(2)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(5)
node7 = TreeNode(4)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if not pRoot:
            return True
        return self.judge(pRoot.left, pRoot.right)
    def judge(self, l, r):
        if not l and not r:
            return True
        if l and r and l.val == r.val:
            return self.judge(l.left,r.right) and self.judge(l.right,r.left)
        return False

if __name__ == '__main__':
    result = Solution().isSymmetrical(node1)
    print(result)