Skip to content

Commit 9461653

Browse files
refactor 589
1 parent 3250759 commit 9461653

File tree

1 file changed

+20
-38
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+20
-38
lines changed
Lines changed: 20 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,31 @@
11
package com.fishercoder.solutions;
22

33
import com.fishercoder.common.classes.Node;
4+
45
import java.util.ArrayList;
56
import java.util.List;
67

7-
/**
8-
* 589. N-ary Tree Preorder Traversal
9-
*
10-
* Given an n-ary tree, return the preorder traversal of its nodes' values.
11-
*
12-
* For example, given a 3-ary tree:
13-
*
14-
* 1
15-
* / | \
16-
* 3 2 4
17-
* / \
18-
* 5 6
19-
*
20-
* Return its preorder traversal as: [1,3,5,6,2,4].
21-
*
22-
* Note:
23-
*
24-
* Recursive solution is trivial, could you do it iteratively?
25-
*/
268
public class _589 {
27-
public static class Solution1 {
28-
public List<Integer> preorder(Node root) {
29-
List<Integer> result = new ArrayList<>();
30-
if (root == null) {
31-
return result;
32-
}
33-
dfs(root, result);
34-
return result;
35-
}
9+
public static class Solution1 {
10+
public List<Integer> preorder(Node root) {
11+
List<Integer> result = new ArrayList<>();
12+
if (root == null) {
13+
return result;
14+
}
15+
dfs(root, result);
16+
return result;
17+
}
3618

37-
private void dfs(Node root, List<Integer> result) {
38-
if (root == null) {
39-
return;
40-
}
41-
result.add(root.val);
42-
if (root.children.size() > 0) {
43-
for (Node child : root.children) {
44-
dfs(child, result);
19+
private void dfs(Node root, List<Integer> result) {
20+
if (root == null) {
21+
return;
22+
}
23+
result.add(root.val);
24+
if (root.children.size() > 0) {
25+
for (Node child : root.children) {
26+
dfs(child, result);
27+
}
28+
}
4529
}
46-
}
4730
}
48-
}
4931
}

0 commit comments

Comments
 (0)