-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1660.java
49 lines (47 loc) · 1.91 KB
/
_1660.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
package com.fishercoder.solutions.secondthousand;
import com.fishercoder.common.classes.TreeNode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _1660 {
public static class Solution1 {
/*
* First off, this problem description is confusing.
* Second, that aside, I learned a cool technique to pass TreeNode[]{node, nodeParent} into the queue
* so that you can easily reference one node's parent without building an additional hashmap.
* Third, there's no easy way to write unit tests for this problem...
*/
public TreeNode correctBinaryTree(TreeNode root) {
Queue<TreeNode[]> q = new LinkedList<>();
q.offer(new TreeNode[] {root, null});
Set<Integer> visited = new HashSet<>();
visited.add(root.val);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode[] curr = q.poll();
TreeNode node = curr[0];
TreeNode nodeParent = curr[1];
if (node.right != null && visited.contains(node.right.val)) {
if (nodeParent.left == node) {
nodeParent.left = null;
} else {
nodeParent.right = null;
}
return root;
}
if (node.left != null) {
q.offer(new TreeNode[] {node.left, node});
visited.add(node.left.val);
}
if (node.right != null) {
q.offer(new TreeNode[] {node.right, node});
visited.add(node.right.val);
}
}
}
return root;
}
}
}