forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_559.java
40 lines (36 loc) · 1.31 KB
/
_559.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.fishercoder.solutions;
import com.fishercoder.common.classes.Node;
import java.util.ArrayList;
import java.util.List;
public class _559 {
public static class Solution1 {
public int maxDepth(Node root) {
int maxDepth = 0;
if (root == null) {
return maxDepth;
}
List<List<Integer>> allPaths = new ArrayList<>();
List<Integer> currentPath = new ArrayList<>();
dfs(root, currentPath, allPaths);
for (List<Integer> path : allPaths) {
maxDepth = Math.max(path.size(), maxDepth);
}
return maxDepth;
}
private void dfs(Node root, List<Integer> currentPath, List<List<Integer>> allPaths) {
if (root == null) {
allPaths.add(new ArrayList<>(currentPath));
}
if (root.children != null && !root.children.isEmpty()) {
currentPath.add(root.val);
for (Node child : root.children) {
dfs(child, new ArrayList<>(currentPath), allPaths);
}
}
if (root.children == null || root.children.isEmpty()) {
currentPath.add(root.val);
allPaths.add(new ArrayList<>(currentPath));
}
}
}
}