You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/*// 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; }};*/classSolution {
publicList<List<Integer>> levelOrder(Noderoot) {
List<List<Integer>> result = newArrayList<>();
if(root == null) returnresult;
Deque<Node> queue = newArrayDeque<>();
queue.offerLast(root);
while(!queue.isEmpty()) {
/* Do a Level Traversal */intsize = queue.size();
List<Integer> list = newArrayList<>();
for(inti = 0; i < size; i++) {
NodecurrentNode = queue.pollFirst();
list.add(currentNode.val);
/* Traverse through current node's all children */List<Node> childrenList = currentNode.children;
for(intj = 0; j < childrenList.size(); j++) {
/* Add the child into temporary list */if(childrenList.get(j) != null) {
queue.offerLast(childrenList.get(j));
}
}
}
/* Gather all results in the same level and insert in the first positoin of the result list */result.add(list);
}
returnresult;
}
}