列表

详情


429. N 叉树的层序遍历

给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。

树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。

 

示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[[1],[3,2,4],[5,6]]

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]

 

提示:

相似题目

二叉树的层序遍历

N 叉树的前序遍历

N 叉树的后序遍历

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<vector<int>> levelOrder(Node* root) { } };

python3 解法, 执行用时: 80 ms, 内存消耗: 18.1 MB, 提交时间: 2024-02-20 09:38:22

"""
# 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]]:
        return [] if not root \
            else [
            [root.val],
            *(sum(e, start=[]) for e in zip_longest(*(self.levelOrder(c) for c in root.children), fillvalue=[]))
        ]

java 解法, 执行用时: 3 ms, 内存消耗: 43.8 MB, 提交时间: 2024-02-20 09:37:31

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        if (root == null) {
            return new ArrayList<List<Integer>>();
        }

        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        Queue<Node> queue = new ArrayDeque<Node>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int cnt = queue.size();
            List<Integer> level = new ArrayList<Integer>();
            for (int i = 0; i < cnt; ++i) {
                Node cur = queue.poll();
                level.add(cur.val);
                for (Node child : cur.children) {
                    queue.offer(child);
                }
            }
            ans.add(level);
        }

        return ans;
    }
}

golang 解法, 执行用时: 0 ms, 内存消耗: 4.2 MB, 提交时间: 2024-02-20 09:36:39

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func levelOrder(root *Node) (ans [][]int) {
    if root == nil {
        return
    }
    q := []*Node{root}
    for q != nil {
        level := []int{}
        tmp := q
        q = nil
        for _, node := range tmp {
            level = append(level, node.Val)
            q = append(q, node.Children...)
        }
        ans = append(ans, level)
    }
    return
}

python3 解法, 执行用时: 64 ms, 内存消耗: 16.9 MB, 提交时间: 2022-08-02 14:32:35

"""
# 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 root is None:
            return []

        que = deque()
        que.append(root)

        res = []

        while que:
            qlen = len(que)
            level = []
            while qlen > 0:
                node = que.popleft()
                for child in node.children:
                    que.append(child)
                
                level.append(node.val)
                qlen -= 1
            
            res.append(level)

        return res

python3 解法, 执行用时: 80 ms, 内存消耗: 17 MB, 提交时间: 2022-08-02 14:31:35

"""
# 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 root is None:
            return []

        que = deque()
        que.append((root, 0))

        res = defaultdict(list)

        while que:
            node, level = que.popleft()
            res[level].append(node.val)

            for child in node.children:
                que.append((child, level + 1))

        res = list(res.values())

        return res

上一题