-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
69 lines (66 loc) · 2.13 KB
/
Solution.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer, List<List<String>>> edges;
private Set<Integer> visited;
private String ans;
public String getDirections(TreeNode root, int startValue, int destValue) {
edges = new HashMap<>();
visited = new HashSet<>();
ans = null;
traverse(root);
dfs(startValue, destValue, new ArrayList<>());
return ans;
}
private void traverse(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
edges.computeIfAbsent(root.val, k -> new ArrayList<>())
.add(Arrays.asList(String.valueOf(root.left.val), "L"));
edges.computeIfAbsent(root.left.val, k -> new ArrayList<>())
.add(Arrays.asList(String.valueOf(root.val), "U"));
}
if (root.right != null) {
edges.computeIfAbsent(root.val, k -> new ArrayList<>())
.add(Arrays.asList(String.valueOf(root.right.val), "R"));
edges.computeIfAbsent(root.right.val, k -> new ArrayList<>())
.add(Arrays.asList(String.valueOf(root.val), "U"));
}
traverse(root.left);
traverse(root.right);
}
private void dfs(int start, int dest, List<String> t) {
if (visited.contains(start)) {
return;
}
if (start == dest) {
if (ans == null || ans.length() > t.size()) {
ans = String.join("", t);
}
return;
}
visited.add(start);
if (edges.containsKey(start)) {
for (List<String> item : edges.get(start)) {
t.add(item.get(1));
dfs(Integer.parseInt(item.get(0)), dest, t);
t.remove(t.size() - 1);
}
}
}
}