Given an n-ary tree, return the preorder traversal of its nodes’ values.
N-ary tree is a rooted tree in which each node has at most N children.
For example, given a 3-ary tree:
1
/|\
3 2 4
/ \
5 6
You should return [1, 3, 5, 6, 2, 4]
in preorder traversal.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
[]
.The preorder traversal visits nodes in the following order:
To implement this iteratively, use a stack:
This approach ensures that nodes are processed in the correct preorder sequence.
Here’s the implementation in C++:
#include <vector>
#include <stack>
using namespace std;
// 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<int> preorder(Node* root) {
vector<int> result;
if (root == nullptr) return result;
stack<Node*> s;
s.push(root);
while (!s.empty()) {
Node* node = s.top();
s.pop();
result.push_back(node->val);
// Push nodes in reverse order of their appearance.
for (int i = node->children.size() - 1; i >= 0; --i) {
s.push(node->children[i]);
}
}
return result;
}
};
O(N)
N
is the total number of nodes in the tree. Each node is visited exactly once.O(N)
O(N)
space complexity.This completes both the recursive and non-recursive (iterative) approaches to solving the problem of N-ary tree preorder traversal.
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?