Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
和Binary Tree的做法一样
/*
// 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>> res = new ArrayList<List<Integer>>();
if(root == null)
return res;
LinkedList<Node> curr = new LinkedList<Node>();
LinkedList<Node> next = new LinkedList<Node>();
List<Integer> line = new ArrayList<Integer>();
curr.offer(root);
while(curr.size() > 0) {
Node temp = curr.poll();
line.add(temp.val);
if(temp.children != null && temp.children.size() > 0) {
for(Node child: temp.children)
next.offer(child);
}
if(curr.size() == 0) {
res.add(line);
line = new ArrayList<Integer>();
curr = next;
next = new LinkedList<Node>();
}
}
return res;
}
}