N 叉樹的層序遍歷

給定一個 N 叉樹,返回其節點值的層序遍歷。 (即從左到右,逐層遍歷)。node

例如,給定一個 3叉樹 :spa

返回其層序遍歷:code

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

說明:blog

  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;
    }
}
相關文章
相關標籤/搜索