N叉树的层序遍历 两种方法 (Python)

队列

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root:
            return []
        dq = collections.deque()
        dq.append(root)
        res_list = []
        while dq:
            tmp_list = []
            for i in range(len(dq)):
                tmp = dq.popleft()
                tmp_list.append(tmp.val)
                dq.extend(tmp.children)
            res_list.append(tmp_list)
        return res_list

数组

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root:
            return []
        level, res_list = [root], []
        while level:
            tmp_res_list = []
            tmp_level = []
            for n in level:
                tmp_res_list.append(n.val)
                tmp_level.extend(n.children)
            res_list.append(tmp_res_list)
            level = tmp_level
        return res_list

你可能感兴趣的:(算法,python,算法)