🌗 429. N 叉树的层序遍历

吞䜛童子2022幎10月10日
  • algorithm
  • tree
  • 层序
小于 1 分钟

🌗 429. N 叉树的层序遍历

隟床: 🌗

问题描述

img_7.png


解法

/*
// 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) {
        // 思路
        // 层序遍历 - 蟅助队列
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        LinkedList<Node> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();
            for(int i = 0; i < len; i ++) {
                Node cur = queue.poll();
                list.add(cur.val);
                // 尝试添加 cur 的子节点入队
                for(Node c: cur.children) {
                    queue.offer(c);
                }
            }
            res.add(list);
        }
        return res;
    }
}

蟓出

img_6.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou