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-postorder-traversal/
思路
递归C++代码
class Solution {
private:
vector<int> result;
void traversal (Node* root) {
if (root == NULL) return;
for (int i = 0; i < root->children.size(); i++) { // 子孩子
traversal(root->children[i]);
}
result.push_back(root->val); // 中
}
public:
vector<int> postorder(Node* root) {
result.clear();
traversal(root);
return result;
}
};
迭代法C++代码
class Solution {
public:
vector<int> postorder(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 = 0; i < node->children.size(); i++) { // 相对于前序遍历,这里反过来
if (node->children[i] != NULL) {
st.push(node->children[i]);
}
}
}
reverse(result.begin(), result.end()); // 反转数组
return result;
}
};