BFS&DFS

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)