Given an n-ary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
An n-ary tree is a tree in which each node has no more than N children. Each node is defined as follows:
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
To achieve the level order traversal of an n-ary tree, we can use a Breadth-First Search (BFS) approach. BFS uses a queue to traverse the tree level by level. Here’s the step-by-step plan:
#include <vector>
#include <queue>
using namespace std;
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) {
vector<vector<int>> result;
if (root == nullptr) {
return result;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int levelSize = q.size();
vector<int> currentLevel;
for (int i = 0; i < levelSize; ++i) {
Node* node = q.front();
q.pop();
currentLevel.push_back(node->val);
for (Node* child : node->children) {
q.push(child);
}
}
result.push_back(currentLevel);
}
return result;
}
};
The time complexity of this solution is (O(N)), where (N) is the number of nodes in the n-ary tree. Each node is processed exactly once.
The space complexity is (O(N)) in the worst case, which occurs when the tree is a complete tree and the last level contains almost (N/2) nodes. This accounts for the space used by the queue.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?