mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
1.2 KiB
1.2 KiB
题目地址
https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
思路
递归C++代码
class Solution {
private:
vector<int> result;
void traversal (Node* root) {
if (root == NULL) return;
result.push_back(root->val);
for (int i = 0; i < root->children.size(); i++) {
traversal(root->children[i]);
}
}
public:
vector<int> preorder(Node* root) {
result.clear();
traversal(root);
return result;
}
};
迭代法C++代码
class Solution {
public:
vector<int> preorder(Node* root) {
vector<int> result;
if (root == NULL) return result;
stack<Node*> st;
st.push(root);
while (!st.empty()) {
Node* node = st.top();
st.pop();
result.push_back(node->val);
// 注意要倒叙,这样才能达到前序(中左右)的效果
for (int i = node->children.size() - 1; i >= 0; i--) {
if (node->children[i] != NULL) {
st.push(node->children[i]);
}
}
}
return result;
}
};