BFS&DFS

2022-04-10  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读