Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc7d73da

Browse files
authored
Update N-ary Tree Postorder Traversal.java
1 parentdd55b2c commitc7d73da

File tree

1 file changed

+20
-27
lines changed

1 file changed

+20
-27
lines changed

‎Easy/N-ary Tree Postorder Traversal.java

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,38 +6,31 @@ class Node {
66
77
public Node() {}
88
9-
public Node(int _val,List<Node> _children) {
9+
public Node(int _val) {
10+
val = _val;
11+
}
12+
13+
public Node(int _val, List<Node> _children) {
1014
val = _val;
1115
children = _children;
1216
}
1317
};
1418
*/
15-
classSolution {
16-
publicList<Integer>postorder(Noderoot) {
17-
List<Integer>values =newArrayList<>();
18-
if (root ==null) {
19-
returnvalues;
20-
}
21-
22-
23-
Stack<Node>stack1 =newStack<>();
24-
Stack<Node>stack2 =newStack<>();
2519

26-
stack1.push(root);
27-
28-
while (!stack1.empty()) {
29-
Nodetemp =stack1.pop();
30-
stack2.push(temp);
31-
List<Node>childrens =temp.children;
32-
for(Nodechildren :childrens) {
33-
stack1.push(children);
34-
}
35-
}
36-
37-
while (!stack2.empty()) {
38-
values.add(stack2.pop().val);
39-
}
40-
41-
returnvalues;
20+
classSolution {
21+
publicList<Integer>postorder(Noderoot) {
22+
List<Integer>result =newArrayList<>();
23+
helper(root,result);
24+
returnresult;
25+
}
26+
27+
privatevoidhelper(Noderoot,List<Integer>result) {
28+
if (root ==null) {
29+
return;
30+
}
31+
for (Nodechild :root.children) {
32+
helper(child,result);
4233
}
34+
result.add(root.val);
35+
}
4336
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp