剑指offer 面试题28 python版+解析:对称的二叉树

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

题目描述

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

思路:前序遍历:先根节点,再左节点,最后右节点。定义对称前序遍历,先根节点,在右节点,最后左节点。要把空节点的情况也考虑到。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if not pRoot:
            return True
        return self.isSame(pRoot.left, pRoot.right)
    def isSame(self,p1,p2):
        if not p1 and not p2:
            return True
        if not p1 or not p2:
            return False
        if p1.val != p2.val:
            return False
        return self.isSame(p1.left, p2.right) and self.isSame(p1.right, p2.left)

猜你喜欢

转载自blog.csdn.net/mabozi08/article/details/88802789