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 = newArrayList<>(); preorder(root, 0, result); return result; }
privatevoidpreorder(Node root, List<List<Integer>> result, int level) { if (root == null) { return; } // expand if (result.size() == level) result.add(newArrayList<>()); // 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.
public List<List<Integer>> levelOrder(Node root) { if (root == null) { returnnewArrayList<>(); } List<List<Integer>> result = newArrayList<>(); Queue<Node> queue = newLinkedList<>(); queue.offer(root); intlevel=0;
while (queue.size() > 0) { // expand result result.add(newArrayList<>()); // queue consists all nodes in the current level intlevelSize= queue.size(); for (inti=0; i < levelSize; ++i) { Nodep= 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; }