# 429.N Ary Tree Level Order Traversal

**429.N ary Tree Lever Order Traversal**

难度:Easy

> 给定一个 N 叉树，返回其节点值的层序遍历。 (即从左到右，逐层遍历)。

例如，给定一个 3叉树 :

![narytreeexample.png](https://i.loli.net/2019/03/30/5c9ee0080a1d8.png)

返回其层序遍历:

```
[
     [1],
     [3,2,4],
     [5,6]
]
```

说明:

树的深度不会超过 1000。 树的节点总数不会超过 5000。

方法：采用了队列的先进后出，迭代遍历所有节点。

```
/*
// 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) {
        deque<Node*> d;
        vector<vector<int>> res;
        if(!root)
            return res;

        d.push_back(root);
        while(!d.empty())
        {
            vector<int >tmp;
            for(auto i: d)
                tmp.push_back(i->val);
            int len=d.size();
            while(len--)
            {
                if(d[0]->children.empty())
                    d.pop_front();
                else
                {

                    for(auto i: d[0]->children)
                        d.push_back(i);
                    d.pop_front();
                }
            }
            res.push_back(tmp);

        }
        return res;

    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/429.n_ary_tree_level_order_traversal.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
