Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> res;
dfs(root, res);
return res;
}
void dfs(Node* root, vector<int>& res) {
if (!root) {
return;
}
res.emplace_back(root->val);
for (auto& x : root->children) {
dfs(x, res);
}
}
};
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> res;
if (!root) {
return res;
}
stack<Node*> s;
s.emplace(root);
while (!empty(s)) {
Node* t = s.top();
res.emplace_back(t->val);
s.pop();
for (auto it = rbegin(t->children); it != rend(t->children); ++it) {
s.emplace(*it);
}
}
return res;
}
};