-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0993-cousins-in-binary-tree.java
More file actions
42 lines (42 loc) · 1.31 KB
/
Copy path0993-cousins-in-binary-tree.java
File metadata and controls
42 lines (42 loc) · 1.31 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
/**
* 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) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
boolean foundX = false;
boolean foundY = false;
int size = q.size();
for (int i=0; i<size; i++) {
TreeNode curr = q.poll();
if (curr.left != null && curr.right != null) {
if (curr.left.val == x && curr.right.val == y ||
curr.left.val == y && curr.right.val == x) {
return false;
}
}
if (curr.val == x) foundX = true;
if (curr.val == y) foundY = true;
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
}
if (foundX && foundY)
return true;
}
return false;
}
}