BFS&DFS

作者: 薛定喵喵喵 | 来源:发表于2022-04-10 16:51 被阅读0次
    from collections import deque
    
    def bfs(root):
        result = []
    
        if root is None:
            return result
    
        q = deque([root])
        while q:
            level = []
            for i in range(len(q)):
                node = q.popleft()
                level.append(node.val)
                for nodechildren in node.childrens:
                         q.append(nodechildren)
            result.append(level)
    
        return result
    

    相关文章

      网友评论

          本文标题:BFS&DFS

          本文链接:https://www.haomeiwen.com/subject/djfcjrtx.html