Use layer-by-layer BFS to solve the problem of "level order traversal of N-ary tree"

6. Level order traversal of N-ary tree

6.1. Requirements for the title

​ Given an N-ary tree, return the level-order traversal of its node values. (ie from left to right, traversing layer by layer).

The serialized input of the tree is traversed in level order, with each set of child nodes separated by a null value (see example).

Example 1:

Please add image description

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

Example 2:

Please add image description

输入: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]]

提示:

树的高度不会超过 1000
树的节点总数在 [0, 10^4] 之间

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

6.2, problem solving ideas

​ Our approach is to add all nodes of the current layer to the result by layer BFS, and then add their child nodes to the next layer. After traversing, replace the current layer with the next layer for traversal.

Please add image description

6.3. Algorithms

class Solution {
    
    
    public List<List<Integer>> levelOrder(Node root) {
    
    
        List<List<Integer>> ans = new ArrayList<>();
        Queue<Node> queue = new ArrayDeque<>();

        //如果root为null,输出空
        if(root == null){
    
    
            return ans;
        }

        queue.offer(root);
        while(!queue.isEmpty()){
    
    
            //当前层的大小
            int cnt = queue.size();
            //每层定义一个新容器
            List<Integer> level = new ArrayList<>();
            //对当前层进行遍历
            for(int i = 0;i < cnt;++i){
    
    
                //将当前节点添加到level中
                Node cur = queue.poll();
                level.add(cur.val);
                //添加ans结果集到下一层
                for(Node child : cur.children){
    
    
                    queue.offer(child);
                }
            }
            ans.add(level);
        }
        return ans;
    }
}

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124051408