-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCousinsInBinaryTree.java
More file actions
62 lines (56 loc) · 1.63 KB
/
CousinsInBinaryTree.java
File metadata and controls
62 lines (56 loc) · 1.63 KB
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
/**
* LeetCode 993 Cousins in Binary Tree
*/
/**
* 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 {
public boolean isCousins(TreeNode root, int x, int y) {
if (root == null) {
return false;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int sz = q.size();
boolean foundX = false;
boolean foundY = false;
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
Set<Integer> set = new HashSet<>();
if (cur.left != null) {
set.add(cur.left.val);
q.offer(cur.left);
}
if (cur.right != null) {
set.add(cur.right.val);
q.offer(cur.right);
}
// check each parent node
if (set.contains(x) && set.contains(y)) {
return false;
} else if (set.contains(x)) {
foundX = true;
} else if (set.contains(y)) {
foundY = true;
}
}
if (foundX && foundY) {
return true;
}
}
return false;
}
}