429. N 叉树的层序遍历(BFS)
作者:互联网
429. N 叉树的层序遍历
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。
示例 1:
输入:root = [1,null,3,2,4,null,5,6] 输出:[[1],[3,2,4],[5,6]]
示例 2:
输入: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] 输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
提示:
- 树的高度不会超过
1000
- 树的节点总数在
[0, 10^4]
之间
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>> ans; 25 if (root == nullptr) { 26 return ans; 27 } 28 queue<Node *> q; 29 q.push(root); 30 while (!q.empty()) { 31 int size = q.size(); 32 vector<int> vec; 33 for (int i = 0; i < size; i++) { 34 Node *tmp = q.front(); 35 q.pop(); 36 if (tmp == nullptr) { 37 continue; 38 } 39 vec.push_back(tmp->val); 40 for (auto &node : tmp->children) { 41 if (node != nullptr) { 42 q.push(node); 43 } 44 } 45 } 46 ans.push_back(vec); 47 } 48 return ans; 49 } 50 };
标签:Node,BFS,val,层序,429,vector,null,root,children 来源: https://www.cnblogs.com/MGFangel/p/16214889.html