429. N-ary Tree Level Order Traversal

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

 

429. N-ary Tree Level Order Traversal_第1张图片

 

We should return its level order traversal:

 

 

[
     [1],
     [3,2,4],
     [5,6]
]

 

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

层次遍历,程序如下所示:

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

    public Node() {}

    public Node(int _val,List _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List> levelOrder(Node root) {
        List> llist = new ArrayList<>();
        if (root == null){
            return llist;
        }
        ArrayDeque que = new ArrayDeque<>();
        que.offer(root);
        while (!que.isEmpty()){
            int size = que.size();
            List list = new ArrayList<>();
            for (int i = 0; i < size; ++ i){
                Node tmp = que.poll();
                list.add(tmp.val);
                for (Node node : tmp.children){
                    if (node != null){
                        que.offer(node);
                    }
                }
            }
            llist.add(list);
        }
        return llist;
    }
}

 

你可能感兴趣的:(LeetCode)