|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import com.fishercoder.common.classes.TreeNode; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.LinkedList; |
| 6 | +import java.util.Queue; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +/** |
| 10 | + * 993. Cousins in Binary Tree |
| 11 | + * |
| 12 | + * In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. |
| 13 | + * Two nodes of a binary tree are cousins if they have the same depth, but have different parents. |
| 14 | + * We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. |
| 15 | + * Return true if and only if the nodes corresponding to the values x and y are cousins. |
| 16 | + * |
| 17 | + * Example 1: |
| 18 | + * 1 |
| 19 | + * / \ |
| 20 | + * 2 3 |
| 21 | + * / |
| 22 | + * 4 |
| 23 | + * |
| 24 | + * Input: root = [1,2,3,4], x = 4, y = 3 |
| 25 | + * Output: false |
| 26 | + * |
| 27 | + * Example 2: |
| 28 | + * 1 |
| 29 | + * / \ |
| 30 | + * 2 3 |
| 31 | + * \ \ |
| 32 | + * 4 5 |
| 33 | + * |
| 34 | + * Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 |
| 35 | + * Output: true |
| 36 | + * |
| 37 | + * Example 3: |
| 38 | + * 1 |
| 39 | + * / \ |
| 40 | + * 2 3 |
| 41 | + * \ |
| 42 | + * 4 |
| 43 | + * |
| 44 | + * Input: root = [1,2,3,null,4], x = 2, y = 3 |
| 45 | + * Output: false |
| 46 | + * |
| 47 | + * |
| 48 | + * Note: |
| 49 | + * |
| 50 | + * The number of nodes in the tree will be between 2 and 100. |
| 51 | + * Each node has a unique integer value from 1 to 100. |
| 52 | + */ |
| 53 | +public class _993 { |
| 54 | + public static class Solution1 { |
| 55 | + public boolean isCousins(TreeNode root, int x, int y) { |
| 56 | + Queue<TreeNode> queue = new LinkedList<>(); |
| 57 | + queue.offer(root); |
| 58 | + while (!queue.isEmpty()) { |
| 59 | + int size = queue.size(); |
| 60 | + for (int i = 0; i < size; i++) { |
| 61 | + TreeNode current = queue.poll(); |
| 62 | + if (current.left != null) { |
| 63 | + queue.offer(current.left); |
| 64 | + } |
| 65 | + if (current.right != null) { |
| 66 | + queue.offer(current.right); |
| 67 | + } |
| 68 | + if (current.left != null && current.right != null) { |
| 69 | + if (current.left.val == x && current.right.val == y |
| 70 | + || current.left.val == y && current.right.val == x) { |
| 71 | + return false; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + if (checkQueue(queue, x, y)) { |
| 76 | + return true; |
| 77 | + } |
| 78 | + } |
| 79 | + return false; |
| 80 | + } |
| 81 | + |
| 82 | + private boolean checkQueue(Queue<TreeNode> queue, int x, int y) { |
| 83 | + Set<Integer> set = new HashSet<>(); |
| 84 | + Queue<TreeNode> tmp = new LinkedList<>(queue); |
| 85 | + while (!tmp.isEmpty()) { |
| 86 | + set.add(tmp.poll().val); |
| 87 | + } |
| 88 | + return set.contains(x) && set.contains(y); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments