第19天。
今天的题目是 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:
1Input: root = [1,null,3,2,4,null,5,6]2Output: [[1],[3,2,4],[5,6]]
Example 2:
1Input: 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]2Output: [[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]
一道水题,简单的BFS
或DFS
即可,除了是一个多叉树外,和另外一道题基本是一样的。
1class Node {2public:3 int val;4 vector<Node*> children;5
6 Node() {}7
8 Node(int _val, vector<Node*> _children) {9 val = _val;10 children = _children;11 }12};
所以,我们既可以用队列去做层次遍历(BFS),也可以用递归来实现DFS,然后按当前节点所在的高度插入到对于的数组即可:
- DFS
1vector<vector<int>> res;2vector<vector<int>> levelOrder(Node* root) {3 dfsWithHeight(root, 0);4 return res;5}6void dfsWithHeight(Node *root, int h) {7 if (root == nullptr) return;8 if (h == res.size()) res.push_back(vector<int>());9 res[h].push_back(root->val);10 for(int i = 0;i < root->children.size(); i++) {11 dfsWithHeight(root->children[i], h + 1);12 }13}
- BFS
1vector<vector<int>> levelOrder2(Node* root) {2 vector<vector<int>> res;3 if (root == nullptr) {4 return res;5 }6 vector<int> vec;7 queue<Node *> q;8 q.push(root);9 q.push(nullptr);10 while(q.size() != 1) {11 vec.clear();12 root = q.front();13 while(root) {14 q.pop();15 vec.push_back(root->val);37 collapsed lines
16 // cout << root->val << endl;17 for(int i = 0;i < root->children.size(); i++) {18 q.push(root->children[i]);19 }20 root = q.front();21 }22 q.pop();23 q.push(nullptr);24 res.push_back(vec);25 }26
27 return res;28}29
30vector<vector<int>> levelOrder1(Node* root) {31 vector<vector<int>> res;32 if (root == nullptr) {33 return res;34 }35 vector<int> vec;36 vector<Node *> nodes;37 vector<Node *> nextLevelNodes;38 nodes.push_back(root);39 while(!nodes.empty()) {40 vec.clear();41 nextLevelNodes.clear();42 for(int i = 0;i < nodes.size(); i++) {43 vec.push_back(nodes[i]->val);44 for(int j = 0;j < nodes[i]->children.size(); j++) {45 nextLevelNodes.push_back(nodes[i]->children[j]);46 }47 }48 swap(nodes, nextLevelNodes);49 res.push_back(vec);50 }51 return res;52}