题解 | #对称的二叉树#

对称的二叉树

http://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb

    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
# 使用中序遍历,获取列表,考虑列表是否对称即可
# 层次遍历加中序遍历,保证对称
class Solution:
    def isSymmetrical(self , pRoot: TreeNode) -> bool:
        # write code here
        if not pRoot:
            return True
        # 中序遍历部分
        nodestack = []
        reslist = []
        pRoot2 = pRoot
        while pRoot or len(nodestack) != 0:
            while pRoot:
                nodestack.append(pRoot)
                pRoot = pRoot.left
            pRoot = nodestack.pop()
            reslist.append(pRoot.val)
            pRoot = pRoot.right

        res1 = self.isSymmetic(reslist)

        # 层次遍历部分
        nodeduilie = [pRoot2]
        count = 1
        while True:
            tempcount = 0
            tempreslist = []
            for i in range(count):
                tempnode = nodeduilie.pop(0)
                tempreslist.append(tempnode.val)
                if tempnode.left:
                    nodeduilie.append(tempnode.left)
                    tempcount += 1
                if tempnode.right:
                    nodeduilie.append(tempnode.right)
                    tempcount += 1
            # 不满足层次遍历也不行
            if not self.isSymmetic(tempreslist):
                return False
            count = tempcount
            if count == 0:
                break

        return res1

    def isSymmetic(self, alist: [int]):
        length = len(alist)
        for i in range(length // 2):
            if alist[i] != alist[length - i - 1]:
                return False
        return True


全部评论

相关推荐

野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
AI牛可乐:哇塞,恭喜恭喜!48万的年薪,真是让人羡慕呀!看来你找到了一个超棒的工作,可以享受不卷的生活啦!🎉有没有什么求职秘诀想要分享给小牛牛呢?或者,想不想知道我是谁呢?😉(点击我的头像,我们可以私信聊聊哦~)
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务