Skip to content

Commit 6823c13

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 42.36%)
1 parent 77a214c commit 6823c13

File tree

1 file changed

+70
-19
lines changed

1 file changed

+70
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,78 @@
1-
// Runtime: 2 ms (Top 20.27%) | Memory: 42 MB (Top 40.06%)
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 41.30 MB (Top 42.36%)
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* public class TreeNode {
6+
* int val;
7+
* TreeNode left;
8+
* TreeNode right;
9+
* TreeNode() {}
10+
* TreeNode(int val) { this.val = val; }
11+
* TreeNode(int val, TreeNode left, TreeNode right) {
12+
* this.val = val;
13+
* this.left = left;
14+
* this.right = right;
15+
* }
16+
* }
17+
*/
218
class Solution {
319
public boolean isCousins(TreeNode root, int x, int y) {
4-
Set<TreeNode> parentSet = new HashSet<>();
5-
Queue<TreeNode> q = new LinkedList<>();
6-
q.add(root);
7-
8-
while (!q.isEmpty()) {
9-
int len = q.size();
10-
11-
for (int i = 0; i < len; i++) {
12-
TreeNode parent = q.remove();
20+
21+
//If any of x or y is at root, it means they can't be at same depth. Return false.
22+
if(root.val == x || root.val == y) return false;
23+
24+
25+
Deque<TreeNode> queue = new LinkedList<>();
26+
queue.offer(root);
27+
28+
boolean xFound = false;
29+
boolean yFound = false;
30+
31+
int parentX = 0;
32+
int parentY = 0;
33+
34+
//Do level-order traversal until x or y is found or queue is empty.
35+
while(!queue.isEmpty() && !xFound && !yFound){
36+
37+
int size = queue.size();
38+
39+
//Traverse that level.
40+
while(size-- > 0){
41+
TreeNode node = queue.poll();
42+
43+
//if x or y is found at left/right, save the parent and set the "found" flag to true.
44+
//This flag will break the loop as soon as any one (x or y) is found.
45+
//we don't need to go deeper to find second if it isn't found at this level.
46+
47+
if(node.left != null) {
48+
queue.offer(node.left);
49+
50+
if(node.left.val == x){
51+
parentX = node.val;
52+
xFound = true;
53+
}
54+
if(node.left.val == y){
55+
parentY = node.val;
56+
yFound = true;
57+
}
58+
59+
}
1360

14-
for (TreeNode child : new TreeNode[]{parent.left, parent.right}) {
15-
if(child != null) {
16-
q.add(child);
17-
if (child.val == x || child.val == y)
18-
parentSet.add(parent);
61+
if(node.right != null) {
62+
queue.offer(node.right);
63+
64+
if(node.right.val == x){
65+
parentX = node.val;
66+
xFound = true;
67+
}
68+
if(node.right.val == y){
69+
parentY = node.val;
70+
yFound = true;
1971
}
2072
}
2173
}
22-
if (parentSet.size() > 0)
23-
return parentSet.size() == 2; //if same parent -> set size wil be 1
74+
2475
}
25-
return false;
76+
return xFound && yFound && parentX != parentY;
2677
}
27-
}
78+
}

0 commit comments

Comments
 (0)