forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCousinsInBinaryTree.java
96 lines (85 loc) · 2.61 KB
/
CousinsInBinaryTree.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* 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;
* }
* }
*/
// Solution I : DFS
class Solution {
private int xDepth = -1;
private int yDepth = -2;
private TreeNode xParent = null;
private TreeNode yParent = null;
public boolean isCousins(TreeNode root, int x, int y) {
if(root == null){
return true;
}
isCousinsHelper(root, x, y, 0, null);
return xDepth==yDepth && xParent !=yParent;
}
private void isCousinsHelper(TreeNode root, int x, int y, int depth, TreeNode parent){
if(root == null){
return ;
}
else if(root.val == x){
xParent = parent;
xDepth = depth;
} else if(root.val == y){
yParent = parent;
yDepth = depth;
} else {
isCousinsHelper(root.left, x, y, depth+1, root);
isCousinsHelper(root.right, x, y, depth+1, root);
}
}
}
// Solution II BFS
class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
if(root == null) return false;
Queue<TreeNode> queue = new LinkedList<>();
TreeNode xParent = null, yParent = null;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
while(size-- > 0){
TreeNode head = queue.poll();
if(head.left != null){
queue.offer(head.left);
if(head.left.val == x){
xParent = head;
}
if(head.left.val == y){
yParent = head;
}
}
if(head.right != null){
queue.offer(head.right);
if(head.right.val == x){
xParent = head;
}
if(head.right.val == y){
yParent = head;
}
}
if(xParent!=null &&yParent!=null){
return xParent != yParent; // equality means not cousins
// non equality means cousins
}
}
if((xParent==null && yParent!=null) || (xParent!=null &&yParent==null)){
return false;
}
}
return false;
}
}