Given an n-ary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Input: [1,null,3,2,4,null,5,6]
Explanation:
1
/ | \
3 2 4 / \ 5 6
Output: [[1], [3,2,4], [5,6]]
N-ary
tree node typically contains a value and a list of its child nodes.import java.util.*;
// Node definition for an N-ary tree
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
public class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
Node current = queue.poll();
level.add(current.val);
for (Node child : current.children) {
queue.offer(child);
}
}
result.add(level);
}
return result;
}
public static void main(String[] args) {
// Example usage:
Node node5 = new Node(5, new ArrayList<>());
Node node6 = new Node(6, new ArrayList<>());
List<Node> children3 = new ArrayList<>(Arrays.asList(node5, node6));
Node node3 = new Node(3, children3);
Node node2 = new Node(2, new ArrayList<>());
Node node4 = new Node(4, new ArrayList<>());
List<Node> children1 = new ArrayList<>(Arrays.asList(node3, node2, node4));
Node root = new Node(1, children1);
Solution solution = new Solution();
List<List<Integer>> result = solution.levelOrder(root);
System.out.println(result); // Output: [[1], [3, 2, 4], [5, 6]]
}
}
The time complexity of this solution is O(N), where N is the number of nodes in the tree. This is because we visit each node exactly once during the BFS traversal.
The space complexity is O(N) for the queue used in the BFS traversal, where N is the number of nodes. This is because, in the worst case, the queue will hold all the nodes at the current level before advancing to the next level.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?