这两道题没什么特别之处
但是从题解中学到了,遍历vector的新方法
/*
// 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<int> preorder(Node* root) {
if (root == nullptr) return {};
vector<int> result = {root->val};
for (auto* child : root->children) { //遍历vector元素 (C++ 11)
vector<int> preorder_child = preorder(child);
result.insert(result.end(), preorder_child.begin(), preorder_child.end());
}
return result;
}
};
//后序
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> result;
if (root) {
vector<int> res;
for (auto & ch : root->children) {
vector<int> r = postorder(ch);
res.insert(res.end(), r.begin(), r.end());
}
result.insert(result.end(), res.begin(), res.end());
result.push_back(root->val);
}
return result;
}
};
关于这个C++ 11 中给出的新方法,见下文: