[LeetCode] 429. N-ary Tree Level Order Traversal

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 (See examples).

Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]

Example 2:

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]]

Constraints:

  • The height of the n-ary tree is less than or equal to 1000
  • The total number of nodes is between [0, 10^4]

N叉树的层序遍历。既然是层序遍历,那么方法一定是BFS跑不了了。如果对层序遍历不熟悉,建议先做一下102题和107题。

时间O(n)

空间O(n)

Java实现

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public List<Node> children;
 6 
 7     public Node() {}
 8 
 9     public Node(int _val) {
10         val = _val;
11     }
12 
13     public Node(int _val, List<Node> _children) {
14         val = _val;
15         children = _children;
16     }
17 };
18 */
19 
20 class Solution {
21     public List<List<Integer>> levelOrder(Node root) {
22         List<List<Integer>> res = new LinkedList<>();
23         // corner case
24         if (root == null) {
25             return res;
26         }
27 
28         // normal case
29         Queue<Node> queue = new LinkedList<>();
30         queue.offer(root);
31         while (!queue.isEmpty()) {
32             List<Integer> list = new ArrayList<>();
33             int size = queue.size();
34             for (int i = 0; i < size; i++) {
35                 Node cur = queue.poll();
36                 list.add(cur.val);
37                 for (Node node : cur.children) {
38                     queue.offer(node);
39                 }
40             }
41             res.add(list);
42         }
43         return res;
44     }
45 }

相关题目

102. Binary Tree Level Order Traversal

107. Binary Tree Level Order Traversal II

429. N-ary Tree Level Order Traversal

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13624589.html