Published
- 1 min read
Given an n-ary tree, return the level order traversal of its nodes values
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]]
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
The snippet shows n-ary level order traversal
private void levelOrdertraversal(Node node) {
//find out their parent level if the parent level is the same then they belong to same group
//at each level update child level, if they belong to same level then while traversal group them
int arr[] = new int[1000];
List<Node> list = new ArrayList<>();
List<List<Node>> listOfNodes = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(node);
arr[node.val] = 0;
list.add(node);
listOfNodes.add(list);
while(queue.isEmpty()) {
Node currentnode = queue.poll();
for (Node child : node.children){
arr[currentnode.val] += 1;
if(listOfNodes.get(arr[currentnode.val])== null) {
ArrayList<Node> newL = new ArrayList<>();
newL.add(child);
} else {
List<Node> l = listOfNodes.get(arr[currentnode.val]);
l.add(child);
}
queue.add(child);
}
}
}