--- tags: leetcode --- # [429. N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/) --- # My Solution ## The Key Idea for Solving This Coding Question BFS ## C++ Code ```cpp= /* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<vector<int>> levelOrder(Node *root) { if (root == nullptr) { return {}; } queue<Node *> q; vector<vector<int>> answer; q.push(root); while (!q.empty()) { int qLen = q.size(); vector<int> oneLevel; for (int i = 0; i < qLen; ++i) { Node *curr = q.front(); q.pop(); oneLevel.push_back(curr->val); for (Node *child : curr->children) { q.push(child); } } answer.push_back(oneLevel); } return answer; } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the n-ary tree referred by `root`. ## Space Complexity $O(n)$ $n$ is the number of nodes in the n-ary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [1,null,3,2,4,null,5,6] ``` ``` [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] ``` ``` [] ``` -->