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

Commita886cc4

Browse files
authored
Update N-ary Tree Preorder Traversal.java
1 parent675c0dc commita886cc4

File tree

1 file changed

+21
-35
lines changed

1 file changed

+21
-35
lines changed

‎Easy/N-ary Tree Preorder Traversal.java

Lines changed: 21 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,47 +6,33 @@ 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-
List<Integer>values =newArrayList<>();
17-
publicList<Integer>preorder(Noderoot) {
18-
updateListIterative(root);
19-
returnvalues;
20-
}
21-
22-
privatevoidupdateListIterative(Noderoot) {
23-
if (root ==null) {
24-
return;
25-
}
26-
27-
Stack<Node>stack =newStack<>();
28-
stack.push(root);
2919

30-
while (!stack.empty()) {
31-
Nodetemp =stack.pop();
32-
values.add(temp.val);
33-
34-
List<Node>childrens =temp.children;
35-
36-
for (inti=childrens.size()-1;i>=0;i--) {
37-
stack.push(childrens.get(i));
38-
}
39-
}
20+
classSolution {
21+
publicList<Integer>preorder(Noderoot) {
22+
if (root ==null) {
23+
returnnewArrayList<>();
4024
}
41-
42-
privatevoidupdateListRecursive(Noderoot) {
43-
if(root ==null) {
44-
return;
45-
}
46-
47-
values.add(root.val);
48-
for (Nodenode :root.children) {
49-
updateListRecursive(node);
50-
}
25+
List<Integer>list =newArrayList<>();
26+
Stack<Node>stack =newStack<>();
27+
stack.push(root);
28+
while (!stack.isEmpty()) {
29+
Nodepopped =stack.pop();
30+
list.add(popped.val);
31+
List<Node>children =popped.children;
32+
for (inti =children.size() -1;i >=0;i--) {
33+
stack.push(children.get(i));
34+
}
5135
}
36+
returnlist;
37+
}
5238
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp