Skip to main content

590.N叉树的后序遍历

::: caution

原题链接:https://leetcode.cn/problems/n-ary-tree-postorder-traversal/

:::

思路

根据后序遍历定义求解

代码

/*
// 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> res;
void dfs(Node* node) {
if (node) {
for (int i = 0; i < node->children.size(); i++) {
dfs(node->children[i]);
res.push_back(node->children[i]->val);
}
}
}

vector<int> postorder(Node* root) {
if (root) {
dfs(root);
res.push_back(root->val);
}
return res;
}
};