剑指—JZ58对称的二叉树

题目描述

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

解题思路

①层次遍历:遍历树的每一层,每一层保存为一个列表,并且节点为None时也要加入,如果不加入,假设层次遍历序列为[[8], [4,4], [1,1]],对于[1, 1],很可能两个1都是右子节点,所以不满足镜像,因此需要加入None,上面假设加入None后为[[8], [4,4], [None,1,1,None]],那么就是镜像对称的。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSymmetrical(self, pRoot):
        if not pRoot:
            return True
        stack = [pRoot]
        res = []
        while stack:
            templen = len(stack)
            templist = []
            for i in range(templen):
                t = stack.pop(0)
                if t is not None:
                    templist.append(t.val)
                    if t.left is None:
                        stack.append(None)
                    else:
                        stack.append(t.left)
                    if t.right is None:
                        stack.append(None)
                    else:
                        stack.append(t.right)
                else:
                    templist.append(None)
            if templist[::-1] != templist:
                return False
        return True

n1 = TreeNode(8)
n21 = TreeNode(4); n22 = TreeNode(4)
n31 = TreeNode(1); n32 = TreeNode(1)
n1.left = n21; n1.right = n22
n21.right = n31; n22.right = n32
S = Solution()
print(S.isSymmetrical(n1))

②递归:对初始的根节点root传两个一样的root去另一个函数judge(pRoot1, pRoot2),保证统一性,如果pRoot1和pRoot2节点同时为空,就可以返回True,如果一个为空,就返回False,这两个作为终止条件,接着进行递归,pRoot1.val == pRoot2.val and judge(pRoot1.left, pRoot2.right) and judge(pRoot1.right, pRoot2.left)

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSymmetrical(self, pRoot):
        return self.judge(pRoot, pRoot)

    def judge(self, pRoot1, pRoot2):
        if pRoot1 is None and pRoot2 is None:
            return True
        if pRoot1 is None or pRoot2 is None:
            return False
        return pRoot1.val == pRoot2.val and self.judge(pRoot1.left, pRoot2.right) and \
               self.judge(pRoot1.right, pRoot2.left)

n1 = TreeNode(8)
n21 = TreeNode(4); n22 = TreeNode(4)
n31 = TreeNode(1); n32 = TreeNode(1)
n1.left = n21; n1.right = n22
n21.right = n31; n22.left = n32
S = Solution()
print(S.isSymmetrical(n1))

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值