【Leetcode】代码随想录Day15|二叉树2.0

文章目录

    • 层序遍历
      • [102 二叉树的层序遍历](#102 二叉树的层序遍历)
    • [226 翻转二叉树](#226 翻转二叉树)
    • [101 对称二叉树](#101 对称二叉树)

层序遍历

队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。

102 二叉树的层序遍历

递归法

python 复制代码
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        levels = []
        self.helper(root, 0, levels)
        return levels
    
    def helper(self, node, level, levels):
        if not node:
            return
        if len(levels) == level:
            levels.append([])
        levels[level].append(node.val)
        self.helper(node.left, level + 1, levels)
        self.helper(node.right, level + 1, levels)

利用长度和队列(迭代)

python 复制代码
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        queue = collections.deque([root])
        result = []
        while queue:
            level = []
            for _ in range(len(queue)):
                cur = queue.popleft()
                level.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
            result.append(level)
        return result

226 翻转二叉树

初始思路

使用递归。先处理root,如果是None,则return None。接着将反转的root.left赋给root.right,另一边也一样。

python 复制代码
class Solution(object):
    def invertTree(self, root):
        if not root:
            return None

        tmp = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(tmp)
        return root

:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充

101 对称二叉树

初始思路

root.left和root.right两个子树在一方反转后是否相等。但空间复杂度不太妙,还需要多traverse一次,应该直接在traverse中查看是否对称。

python 复制代码
class Solution(object):
    def invertTree(self, root):
        if not root:
            return None
        
        tmp = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(tmp)
        return root

    def compare(self, left, right):
        if not left and not right:
            return True
        if not left or not right:
            return False
        if left.val == right.val:
            return self.compare(left.left, right.left) and self.compare(left.right, right.right)
        return False

    def isSymmetric(self, root):
        # invert tree and see if it is the same as itself
        if not root:
            return True

        invert_left = self.invertTree(root.left)
        return self.compare(invert_left, root.right)

代码随想录

python 复制代码
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        return self.compare(root.left, root.right)
        
    def compare(self, left, right):
        #首先排除空节点的情况
        if left == None and right != None: return False
        elif left != None and right == None: return False
        elif left == None and right == None: return True
        #排除了空节点,再排除数值不相同的情况
        elif left.val != right.val: return False
        
        #此时就是:左右节点都不为空,且数值相同的情况
        #此时才做递归,做下一层的判断
        outside = self.compare(left.left, right.right) #左子树:左、 右子树:右
        inside = self.compare(left.right, right.left) #左子树:右、 右子树:左
        isSame = outside and inside #左子树:中、 右子树:中 (逻辑处理)
        return isSame

:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充

相关推荐
TF男孩13 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在18 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
NAGNIP20 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
站大爷IP20 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
美团技术团队21 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法