-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCousinsInBinaryTree_07May.java
More file actions
74 lines (70 loc) · 2.14 KB
/
CousinsInBinaryTree_07May.java
File metadata and controls
74 lines (70 loc) · 2.14 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
63
64
65
66
67
68
69
70
71
72
73
74
/**
* 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;
* }
* }
*/
/*
Used Traditional approach (By Using Queue) to traverse a binary tree , Time Complexity of below pgm is O(n)
and space complexity will be O(n+h) where h is no of levels in binary tree
*/
class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
if(root.val == x || root.val ==y) {
return false;
}
if(x == y) {
return true;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(null);
int parentX = 0;
int parentY = 0;
while(!q.isEmpty()) {
TreeNode temp = q.poll();
if(temp == null) {
q.add(null);
if(parentX == 0 && parentY ==0) {
continue;
}
if(parentX == 0 || parentY == 0) {
q = null;
return false;
}
if(parentX != parentY) {
return true;
} else {
return false;
}
} else {
if(temp.left!=null) {
if(temp.left.val == x) {
parentX = temp.val;
} else if (temp.left.val == y) {
parentY = temp.val;
}
q.add(temp.left);
}
if(temp.right!=null) {
if(temp.right.val == x) {
parentX = temp.val;
} else if (temp.right.val == y) {
parentY = temp.val;
}
q.add(temp.right);
}
}
}
return false;
}
}