Reference: LeetCode
Difficulty: Easy

Problem

Given an n-ary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

Example:

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

Note:

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

Analysis

Recursion

The recursion is actually based on the preorder traversal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> result = new ArrayList<>();
preorder(root, 0, result);
return result;
}

private void preorder(Node root, List<List<Integer>> result, int level) {
if (root == null) {
return;
}
// expand
if (result.size() == level) result.add(new ArrayList<>());
// visit
result.get(level).add(root.val);
// children
for (Node n : root.children) {
preorder(n, result, level + 1); // no need to check null
}
}

Time: $O(N)$
Space: $O(N)$ to store all nodes.

Iteration

In the foreach statement, if p.children is null, it would crash. However, if a node is in p.children, it can’t be null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public List<List<Integer>> levelOrder(Node root) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
int level = 0;

while (queue.size() > 0) {
// expand result
result.add(new ArrayList<>());
// queue consists all nodes in the current level
int levelSize = queue.size();
for (int i = 0; i < levelSize; ++i) {
Node p = queue.poll();
result.get(level).add(p.val);
// offer children into queue
for (Node child : p.children) {
queue.offer(child); // no null check
}
}
++level;
}
return result;
}

Time: $O(N)$
Space: $O(N)$ to store all nodes.


Comment