leetcode講解--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).java

For example, given a 3-ary tree:node

We should return its level order traversal:spa

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

Note:code

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

[題目地址]https://leetcode.com/problems...遞歸

講解

這道題我真的想了有好久,剛開始想用隊列,可是發現不知道怎麼分割每一層,因而就想仍是用遞歸。後來愈加想不明白,最後看了別人的解法。其實分割每一層是能夠作到的。之後要多練習。隊列

java代碼

/*
// 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 {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> levelOrder(Node root) {
        if(root==null){
            return result;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        int children_num = 1;
        List<Integer> rootList = new ArrayList<Integer>();
        rootList.add(root.val);
        result.add(rootList);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int count=0;
            for(int i=0;i<children_num;i++){
                Node now = queue.poll();
                if(now.children!=null){
                    for(Node node:now.children){
                        queue.offer(node);
                        list.add(node.val);
                        count++;
                    }
                }
            }
            children_num = count;
            if(list.size()>0){
                result.add(list);
            }
        }
        return result;
    }
}
相關文章
相關標籤/搜索