LEETCODE-DAY15


title: LEETCODE-DAY15
date: 2024-03-07 14:06:12
tags:

今日内容: 层序遍历 (共10题) 226.翻转二叉树 、101.对称二叉树 2

1.层序遍历(T102为模板)

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        res=list()
        q=deque()
        if root:
            q.append(root)
        while q:
            level=list()#存放每一层的节点
            size=len(q)
            for i in range(size):
                temp=q.popleft()
                if temp.left:
                    q.append(temp.left)
                if temp.right:
                    q.append(temp.right)
                level.append(temp.val)
            res.append(level)
        return res

python语法:1.列表的嵌套:这里level也是一个列表

时间有点紧后面再补

2.翻转二叉树

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return []
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

TypeError: [] is not valid value for the expected return type TreeNode

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

AC



3.对称二叉树

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def leftTra(self,root):
            res1=list()
            if not root:
                return []
            left=leftTra(self,root.left)
            right=leftTra(self,root.right)
            return [root.val]+left+right
        def rightTra(self,root):
            res1=list()
            if not root:
                return []
            right=leftTra(self,root.right)
            left=leftTra(self,root.left)
            return [root.val]+right+left
        return leftTra(self,root)!=rightTra(self,root)

想法是leftTra以中左右遍历,rightTra以中右左遍历

root =
[1]

输出
false
预期结果
true

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        return self.compare(root.left, root.right)

    def compare(self, cur_left, cur_right):
        #首先排除空节点的情况
        if cur_left is None and cur_right is not None:
            return False
        elif cur_left is not None and cur_right is None:
            return False
        elif cur_left is None and cur_right is None:
            return True
        # 不为空的,但是值不想等
        elif cur_left.val != cur_right.val:
            return False
        else:
            # 左右节点不为空,且数字相等
            outside = self.compare(cur_left.left,cur_right.right)
            inside = self.compare(cur_left.right, cur_right.left)
            return outside and inside
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值