N 叉树的层序遍历

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

返回其层序遍历:

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

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 5000
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> list = new LinkedList<>();
        if(root==null) return list;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        int first = 1;
        int second = 0;
        List<Integer> temp = new LinkedList<>();
        while(!queue.isEmpty()){
            Node node = queue.poll();
            first--;
            temp.add(node.val);
            Iterator<Node> iterator = node.children.iterator();
            while(iterator.hasNext()){
                Node cur = iterator.next();
                queue.offer(cur);
                second++;
            }
            if(first==0){
                list.add(temp);
                first = second;
                second = 0;
                temp = new LinkedList<>();
            }
        }
        return list;
    }
}

 

posted @ 2019-06-09 20:14  Cyrus丶  阅读(309)  评论(0编辑  收藏  举报