You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md
+47-39
Original file line number
Diff line number
Diff line change
@@ -37,7 +37,11 @@
37
37
38
38
## Solutions
39
39
40
-
### Solution 1
40
+
### Solution 1: Recursion
41
+
42
+
We can recursively traverse the entire tree. For each node, we first recursively call the function for each of the node's children, then add the node's value to the answer.
43
+
44
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.
41
45
42
46
<!-- tabs:start -->
43
47
@@ -86,11 +90,9 @@ class Node {
86
90
*/
87
91
88
92
classSolution {
89
-
90
-
privateList<Integer> ans;
93
+
privateList<Integer> ans =newArrayList<>();
91
94
92
95
publicList<Integer>postorder(Noderoot) {
93
-
ans =newArrayList<>();
94
96
dfs(root);
95
97
return ans;
96
98
}
@@ -132,15 +134,18 @@ class Solution {
132
134
public:
133
135
vector<int> postorder(Node* root) {
134
136
vector<int> ans;
135
-
dfs(root, ans);
137
+
function<void(Node*)> dfs = [&](Node* root) {
138
+
if (!root) {
139
+
return;
140
+
}
141
+
for (auto& child : root->children) {
142
+
dfs(child);
143
+
}
144
+
ans.push_back(root->val);
145
+
};
146
+
dfs(root);
136
147
return ans;
137
148
}
138
-
139
-
void dfs(Node* root, vector<int>& ans) {
140
-
if (!root) return;
141
-
for (auto& child : root->children) dfs(child, ans);
We use a stack to help us get the post-order traversal. We first push the root node into the stack. Since the post-order traversal is left subtree, right subtree, root, and the characteristic of the stack is first in last out, we first add the node's value to the answer, then push each of the node's children into the stack in the order from left to right. This way, we can get the traversal result of root, right subtree, left subtree. Finally, we reverse the answer to get the post-order traversal result.
213
+
214
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.
205
215
206
216
<!-- tabs:start -->
207
217
@@ -294,13 +304,17 @@ class Solution {
294
304
public:
295
305
vector<int> postorder(Node* root) {
296
306
vector<int> ans;
297
-
if (!root) return ans;
307
+
if (!root) {
308
+
return ans;
309
+
}
298
310
stack<Node*> stk{{root}};
299
311
while (!stk.empty()) {
300
312
root = stk.top();
301
313
ans.push_back(root->val);
302
314
stk.pop();
303
-
for (Node* child : root->children) stk.push(child);
0 commit comments