算法: 二叉树级顺序遍历 (3种解法)102. Binary Tree Level Order Traversal

Posted AI架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 二叉树级顺序遍历 (3种解法)102. Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。

102. Binary Tree Level Order Traversal

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

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: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

1. BFS广度优先 解法一

level是当前关卡中的节点列表。继续将这些节点的值列表附加到下一个级别(孩子)中的所有节点ans,然后更新level,直到它达到一个空级别。Python 的列表推导使得以简洁的方式处理许多条件变得更加容易。

def levelOrder(self, root):
    if not root:
        return []
    ans, level = [], [root]
    while level:
        ans.append([node.val for node in level])
        temp = []
        for node in level:
            temp.extend([node.left, node.right])
        level = [leaf for leaf in temp if leaf]
    return ans

2. BFS 简化解法二

def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])
        LRpair = [(node.left, node.right) for node in level]
        level = [leaf for LR in LRpair for leaf in LR if leaf]
    return ans

3. BFS 简化解法三

def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])            
        level = [kid for n in level for kid in (n.left, n.right) if kid]
    return ans

参考

https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33464/5-6-lines-fast-python-solution-(48-ms)

以上是关于算法: 二叉树级顺序遍历 (3种解法)102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcode算法总结 —— 二叉树前中后序遍历(迭代和递归两种解法)

LeetCode 102 Binary Tree Level Order Traversal(二叉树的层级顺序遍历)(*)

LeetCode102. Binary Tree Level Order Traversal-二叉树水平顺序遍历

图解 二叉树的四种遍历

Leetcode(102)-二叉树的层次遍历

LeetCode-102-二叉树的层序遍历