问题:
给定N叉树,将各个节点的值,按【层】构成数组输出。
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, 104]
example 1:
example 2:
解法:BFS
遍历树,对当前节点,将其children节点加入queue。
遍历每层queue,按层加入group
再将group存入res。
代码参考:
1 /* 2 // Definition for a Node. 3 class Node { 4 public: 5 int val; 6 vector<Node*> children; 7 8 Node() {} 9 10 Node(int _val) { 11 val = _val; 12 } 13 14 Node(int _val, vector<Node*> _children) { 15 val = _val; 16 children = _children; 17 } 18 }; 19 */ 20 21 class Solution { 22 public: 23 vector<vector<int>> levelOrder(Node* root) { 24 vector<vector<int>> res; 25 queue<Node*>q; 26 if(root) q.push(root); 27 while(!q.empty()) { 28 int sz=q.size(); 29 vector<int> group; 30 for(int i=0; i<sz; i++) { 31 Node* cur = q.front(); 32 group.push_back(cur->val); 33 q.pop(); 34 for(Node*p:cur->children) { 35 if(p){ 36 q.push(p); 37 } 38 } 39 } 40 res.push_back(group); 41 } 42 return res; 43 } 44 };