- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1740.java
76 lines (70 loc) · 2.61 KB
/
_1740.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
70
71
72
73
74
75
76
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.*;
publicclass_1740 {
publicstaticclassSolution1 {
/*
* My completely original solution on 6/30/2024.
*/
publicintfindDistance(TreeNoderoot, intp, intq) {
// dfs to find either p or q first, then add it into a queue, also form a child to
// parent mapping
Queue<TreeNode> queue = newLinkedList<>();
Map<TreeNode, TreeNode> childToParent = newHashMap<>();
dfs(root, p, q, queue, childToParent);
inttarget = queue.peek().val == p ? q : p;
intdistance = 0;
Set<Integer> visited =
newHashSet<>(); // this visited collection is often very essential to prevent
// infinite loop.
visited.add(queue.peek().val);
while (!queue.isEmpty()) {
intsize = queue.size();
for (inti = 0; i < size; i++) {
TreeNodecurr = queue.poll();
if (curr == null) {
continue;
}
if (curr.val == target) {
returndistance;
}
if (curr.left != null && visited.add(curr.left.val)) {
queue.offer(curr.left);
}
if (curr.right != null && visited.add(curr.right.val)) {
queue.offer(curr.right);
}
if (childToParent.containsKey(curr)
&& visited.add(childToParent.get(curr).val)) {
queue.offer(childToParent.get(curr));
}
}
distance++;
}
returndistance;
}
privatevoiddfs(
TreeNoderoot,
intp,
intq,
Queue<TreeNode> queue,
Map<TreeNode, TreeNode> childToParent) {
if (root == null) {
return;
}
if (root.val == p || root.val == q) {
if (queue.isEmpty()) {
queue.offer(root);
}
}
if (root.left != null) {
childToParent.put(root.left, root);
}
dfs(root.left, p, q, queue, childToParent);
if (root.right != null) {
childToParent.put(root.right, root);
}
dfs(root.right, p, q, queue, childToParent);
}
}
}