Given an n-ary tree, return the level order traversal of its nodes ' values. (ie, from left-to-right, level by level).
For example, given a 3-ary
tree:
We should return its level order traversal:
[ 1], [3,2,4], [5,6]]
Note:
- The depth of the tree are at most
1000
.
- The total number of nodes are at most
5000
.
The previous sequential record node is located at that level.
#include <vector>#include<cstdlib>#include<iostream>#include<unordered_set>#include<algorithm>#include<string>using namespacestd;//Definition for a Node.classNode { Public: intval =NULL; Vector<node *>children; Node () {} node (int_val, Vector<node *>_children) {Val=_val; Children=_children; }};classSolution { Public: Vector<vector<int>> Levelorder (Node *root) {Vector<vector<int>>Res; Preorder (root, res,0); returnRes; } voidPreorder (Node *root, vector<vector<int>> &res,intLevel ) { if(Root = NULL)return; if(Res.size () < level +1) Res.push_back ({}); Res[level].push_back (Root-val); for(inti =0; I < root->children.size (); ++i) {Preorder (root->children[i], res, level +1); } }};intMain () {Node*NODE5 =NewNode (5, {}); Node*node6 =NewNode (6, {}); Node*node3 =NewNode (3, {node5, node6}); Node*node2 =NewNode (2, {}); Node*node4 =NewNode (4, {}); Node*node1 =NewNode (1, {node3, Node2, node4}); Solution solution; Vector<vector<int>> res =Solution.levelorder (Node1); for(inti =0; I < res.size (); ++i) { for(intj =0; J < Res[i].size (); ++j) cout<< Res[i][j] <<" "; cout<<Endl; } return 0;}
Less efficient than 3.97 of submissions
Your runtime beats 3.97% of CPP submissions.
Reference discussion area, using queues to store node pointers. Every time the while loop starts, the queue stores all the node pointers in one layer. This time Your runtime beats 12.71% of CPP
classSolution { Public: Vector<vector<int>> Levelorder (Node *root) {Vector<vector<int>>Res; if(Root = =NULL)returnRes; Queue<node *>Q; Q.push (root); while(!Q.empty ()) {Vector<int>Level ; intSize =q.size (); for(inti =0; i < size; ++i) {Node*top =Q.front (); Q.pop (); Level.push_back (Top-val); for(intj =0; J < Top->children.size (); ++j) {Q.push (top-Children[j]); } }//for (int i = 0; i < level.size (); ++i)//cout << level[i] << "";//cout << Endl;res.push_back (level); } returnRes; }};
429. N-ary Tree level Order traversal