Skip to content

Files

Latest commit

Apr 1, 2020
a548e13 · Apr 1, 2020

History

History
executable file
·
64 lines (49 loc) · 1.26 KB

0429. N-ary Tree Level Order Traversal.md

File metadata and controls

executable file
·
64 lines (49 loc) · 1.26 KB

0429. N-ary Tree Level Order Traversal, easy, , freq: 4.%, acceptance: 60.2%

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 is at most 1000. The total number of nodes is at most 5000.

// 160ms, 24%
/*
// 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) return res;
        vector<Node*> buf;
        buf.push_back(root);
        while (!buf.empty()) {
            vector<Node*> tmpBuf;
            tmpBuf.reserve(buf.size());
            res.push_back({});
            for (const auto& r : buf) {
                res.back().push_back(r->val);
                if (!r->children.empty())
                    tmpBuf.insert(tmpBuf.end(), r->children.begin(), r->children.end());
            }
            buf.swap(tmpBuf);
        }
        return res;
    }
};