|
| 1 | +package com.fishercoder.solutions.secondthousand; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | + |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.Queue; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +public class _1660 { |
| 11 | + public static class Solution1 { |
| 12 | + /** |
| 13 | + * First off, this problem description is confusing. |
| 14 | + * Second, that aside, I learned a cool technique to pass TreeNode[]{node, nodeParent} into the queue |
| 15 | + * so that you can easily reference one node's parent without building an additional hashmap. |
| 16 | + * Third, there's no easy way to write unit tests for this problem... |
| 17 | + */ |
| 18 | + public TreeNode correctBinaryTree(TreeNode root) { |
| 19 | + Queue<TreeNode[]> q = new LinkedList<>(); |
| 20 | + q.offer(new TreeNode[]{root, null}); |
| 21 | + Set<Integer> visited = new HashSet<>(); |
| 22 | + visited.add(root.val); |
| 23 | + while (!q.isEmpty()) { |
| 24 | + int size = q.size(); |
| 25 | + for (int i = 0; i < size; i++) { |
| 26 | + TreeNode[] curr = q.poll(); |
| 27 | + TreeNode node = curr[0]; |
| 28 | + TreeNode nodeParent = curr[1]; |
| 29 | + if (node.right != null && visited.contains(node.right.val)) { |
| 30 | + if (nodeParent.left == node) { |
| 31 | + nodeParent.left = null; |
| 32 | + } else { |
| 33 | + nodeParent.right = null; |
| 34 | + } |
| 35 | + return root; |
| 36 | + } |
| 37 | + if (node.left != null) { |
| 38 | + q.offer(new TreeNode[]{node.left, node}); |
| 39 | + visited.add(node.left.val); |
| 40 | + } |
| 41 | + if (node.right != null) { |
| 42 | + q.offer(new TreeNode[]{node.right, node}); |
| 43 | + visited.add(node.right.val); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return root; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments