letecode [429] - N-ary Tree Level Order Traversal

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:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Subject to the effect :

  Given an N-tree, its output level through the results.

Understanding:

  Traverse the level generally require the use of the queue. Before each calculation of the size of the queue traversal layer, the current layer is the number of nodes of the size of the current queue.

Code C ++:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        vector<vector<int>> res;
        if(root == NULL)
            return res; 
        int currentLaySize,k;
        queue<Node*> q;
        q.push(root);
        Node* node;
        while(!q.empty()){
            vector<int> layer;
            currentLaySize = q.size();
            while(currentLaySize){
                node = q.front();
                layer.push_back(node->val);
                q.pop();
                k=0;
                while(k<(node->children).size()){
                    q.push((node->children)[k]);
                    k++;
                }
                currentLaySize--;
            }
            res.push_back(layer);
        }
        return res;
    }
};

operation result:

  When execution: 220 ms, beat the 88.43% of all users to submit in C ++

  Memory consumption: 33.7 MB, defeated 72.68% of all users to submit in C ++

Guess you like

Origin www.cnblogs.com/lpomeloz/p/11084180.html