0429. N Ary Tree Level Order Traversal

0429. N-ary Tree Level Order Traversal #

题目 #

给定一个 N 叉树,返回其节点的 层序遍历

思路 #

代码 #

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>> ans = new LinkedList<>();
        if (root == null) return ans;
        
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            int layerSize = queue.size();
            ans.add(new LinkedList<>());
            for (int i = 0; i < layerSize; i++) {
                Node node = queue.poll();
                ans.get(ans.size() - 1).add(node.val);
                for (Node child: node.children) queue.offer(child);
            }
        }
        
        return ans;
    }
}