首页 > 后端开发 > Python教程 > 二叉树层次顺序遍历 Leetcode

二叉树层次顺序遍历 Leetcode

Linda Hamilton
发布: 2025-01-05 04:05:39
原创
747 人浏览过

给定二叉树的根,返回其节点值的级别顺序遍历。 (即从左到右,逐级)。

Binary Tree Level Order Traversal Leetcode

Example 1:
Input: root = [3,9,20,null,null,15,7] 
Output: [[3],[9,20],[15,7]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []
登录后复制

二叉树层次顺序遍历Python解决方案

class Solution(object):
    def levelOrder(self, root):
        if not root:
            return []
        Q = deque([root])
        levels = [[root.val]]
        temp = deque()
        while Q:
            node = Q.popleft()
            if node.left: temp.append(node.left)
            if node.right: temp.append(node.right)
            if not Q:
                if temp:
                    levels.append([n.val for n in temp])
                Q = temp
                temp = deque()
        return levels
登录后复制

本解决方案中使用的编码模式

所有提供的实现中使用的编码模式是树广度优先搜索(BFS)
此模式通常逐层遍历树,在移动到下一个深度之前处理当前深度的所有节点。
BFS 使用队列数据结构来实现,以跟踪每个级别的节点。

该解决方案的时间和空间复杂度

  1. 时间复杂度为 O(N),因为每个节点都被访问一次。
  2. 空间复杂度为 O(M),因为队列(或递归堆栈)在任何级别都能容纳最大数量的节点。

参考:

  1. LeetCode 问题
  2. LeetCode 解决方案
  3. 广度优先搜索

以上是二叉树层次顺序遍历 Leetcode的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板