python - BFS 检索每个顺序中值的元素

标签 python algorithm breadth-first-search

我试图解决问题Binary Tree Level Order Traversal - LeetCode

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example: Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

我的解决方案很直观,BFS遍历并收集每一层的值

from collections import deque
class Solution:
    def levelOrder(self, root):
        if not root: return [] #base case 
        res = []
        #queue to colloct all the nodes
        queue = deque([root]) 

        while queue:
            level_vals = [] #hold the values at the current level.
            for _ in range(len(queue)): #evalute once before execution enter the loop
                cur = queue.popleft()
                if node.left:
                    queue.append(cur.left)
                if node.right:
                    queue.append(cur.right)
                level_vals.append(cur.val)
            res.append(level_vals)
        return res 

我在讨论区看到了这样一个bfs和queue soltion

# BFS + deque
def levelOrder(self, root):
    res, queue = [], deque([(root, 0)])
    while queue:
        cur, level = queue.popleft()
        if cur:
            if len(res) < level+1:
                res.append([])
            res[level].append(cur.val)
            queue.append((cur.left, level+1))
            queue.append((cur.right, level+1))
    return res

我对条件检查感到困惑 if len(res) < level+1: res.append([]) , 并认为它可以是 '

        if cur:
            #if len(res) < level+1:
            res.append([])
            res[level].append(cur.val)
            queue.append((cur.left, level+1))
            queue.append((cur.right, level+1))
    return res

为什么需要条件检查?

最佳答案

只有在 queue 中遇到新级别时,才会将新数组(对应于新级别)附加到 res 中。如果没有该检查,代码将为 queue 中遇到的每个节点向 res 附加一个新的空数组。

让我们看看当您运行带有条件检查的代码时会发生什么。对于您的示例树,首先从队列中弹出值为 3 的根节点。此时res的长度为0,level也为0。所以 len(res) > level + 1 是真的。因此,一个新的空数组被附加到 res 以存储树级别 0 的值。处理级别 1 的第一个节点(值为 9)时也是如此。但是,处理完之后,当我们开始处理第 1 层的第二个节点(值为 20)时,res 数组有 2 个元素(每个层一个),level 的值为 1。 len(res) > level + 1 为 false,没有任何内容插入到 res

如果没有这个检查,res 数组在迭代结束时会是这样的:

[
  [3],
  [9, 20],
  [15, 7],
  [],
  []
]

请注意,因为您的树中有 5 个节点,所以总共有 5 个数组附加到 res 但只有前 3 个被占用,因为您的树有 3 个级别。

关于python - BFS 检索每个顺序中值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55608344/

相关文章:

python - 识别标签结构不同的分支

python - 用 Python 实现了广度优先搜索算法。不知道如何返回解决方案

algorithm - 使用 BFS 检查循环图

python - 为二叉树实现 DFS 和 BFS

python - 使用 Python 对 DataFrame 中的 header 进行排序

python - 如何使用 xmpppy 发送数据?

python matplotlib 绘制日期时间索引

java - 在二叉搜索树中寻找中序后继

algorithm - 从日志中过滤掉相似的行

c# GDI 边缘空白检测算法