429. N叉树的层序遍历

广度优先搜索

class Solution {
    public List<List<Integer>> levelOrder(Node root) {

        List<List<Integer>> list = new LinkedList<>();
        Queue<Node> queue = new LinkedList<>();

        if (root == null){
            return list;
        }

        queue.add(root);

        while (!queue.isEmpty()){

            int size = queue.size();
            List<Integer> li = new LinkedList<>();

            for (int i = 0; i < size; i++) {

                Node temp = queue.poll();
                li.add(temp.val);

                /**
                 * 由于是N叉树,因此遍历每一个孩子加入
                 */
                for (Node c : temp.children){
                    queue.add(c);
                }
            }

            list.add(li);
        }

        return list;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/

posted @ 2022-02-21 12:05  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报