Skip to content

Commit 9d1d779

Browse files
refactor 559
1 parent 26356cb commit 9d1d779

File tree

1 file changed

+29
-49
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+29
-49
lines changed
Lines changed: 29 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,40 @@
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-
* 559. Maximum Depth of N-ary Tree
9-
*
10-
* Given a n-ary tree, find its maximum depth.
11-
*
12-
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
13-
*
14-
* For example, given a 3-ary tree:
15-
* 1
16-
* / | \
17-
* 3 2 4
18-
* / \
19-
* 5 6
20-
*
21-
* We should return its max depth, which is 3.
22-
*
23-
* Note:
24-
*
25-
* The depth of the tree is at most 1000.
26-
* The total number of nodes is at most 5000.
27-
*/
288
public class _559 {
29-
public static class Solution1 {
30-
public int maxDepth(Node root) {
31-
int maxDepth = 0;
32-
if (root == null) {
33-
return maxDepth;
34-
}
35-
List<List<Integer>> allPaths = new ArrayList<>();
36-
List<Integer> currentPath = new ArrayList<>();
37-
dfs(root, currentPath, allPaths);
38-
for (List<Integer> path : allPaths) {
39-
maxDepth = Math.max(path.size(), maxDepth);
40-
}
41-
return maxDepth;
42-
}
9+
public static class Solution1 {
10+
public int maxDepth(Node root) {
11+
int maxDepth = 0;
12+
if (root == null) {
13+
return maxDepth;
14+
}
15+
List<List<Integer>> allPaths = new ArrayList<>();
16+
List<Integer> currentPath = new ArrayList<>();
17+
dfs(root, currentPath, allPaths);
18+
for (List<Integer> path : allPaths) {
19+
maxDepth = Math.max(path.size(), maxDepth);
20+
}
21+
return maxDepth;
22+
}
4323

44-
private void dfs(Node root, List<Integer> currentPath, List<List<Integer>> allPaths) {
45-
if (root == null) {
46-
allPaths.add(new ArrayList<>(currentPath));
47-
}
48-
if (root.children != null && !root.children.isEmpty()) {
49-
currentPath.add(root.val);
50-
for (Node child : root.children) {
51-
dfs(child, new ArrayList<>(currentPath), allPaths);
24+
private void dfs(Node root, List<Integer> currentPath, List<List<Integer>> allPaths) {
25+
if (root == null) {
26+
allPaths.add(new ArrayList<>(currentPath));
27+
}
28+
if (root.children != null && !root.children.isEmpty()) {
29+
currentPath.add(root.val);
30+
for (Node child : root.children) {
31+
dfs(child, new ArrayList<>(currentPath), allPaths);
32+
}
33+
}
34+
if (root.children == null || root.children.isEmpty()) {
35+
currentPath.add(root.val);
36+
allPaths.add(new ArrayList<>(currentPath));
37+
}
5238
}
53-
}
54-
if (root.children == null || root.children.isEmpty()) {
55-
currentPath.add(root.val);
56-
allPaths.add(new ArrayList<>(currentPath));
57-
}
5839
}
59-
}
6040
}

0 commit comments

Comments
 (0)