Skip to content

Commit 36c0091

Browse files
committed
993. Cousins in Binary Tree (easy)
1 parent fb53371 commit 36c0091

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

dsa-trees/readme.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ list of standard Tree problems which are solved in this repo with explaination
1111
* *[872. Leaf-Similar Trees (easy)](https://leetcode.com/problems/leaf-similar-trees/)*
1212
* *[257. Binary Tree Paths (easy)](https://leetcode.com/problems/binary-tree-paths/)*
1313
* *[404. Sum of Left Leaves (easy)](https://leetcode.com/problems/sum-of-left-leaves/)*
14-
* *[112. Path Sum (easy)](https://leetcode.com/problems/path-sum/)*
14+
* *[112. Path Sum (easy)](https://leetcode.com/problems/path-sum/)*
15+
* *[993. Cousins in Binary Tree (easy)](https://leetcode.com/problems/cousins-in-binary-tree/)*
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
*
3+
*/
4+
5+
/**
6+
* @author dhananjay
7+
* @link : https://leetcode.com/problems/cousins-in-binary-tree/
8+
* @level : easy
9+
*/
10+
public class LC993_CousinsInBinaryTree {
11+
public boolean isCousins(TreeNode root, int x, int y) {
12+
13+
int[] parents = new int[2];
14+
int[] levels = new int[2];
15+
16+
findParentAndLevel(root, new TreeNode(-1), 0, x, y, parents, levels);
17+
return parents[0] != parents[1] && levels[0] == levels[1];
18+
}
19+
20+
private void findParentAndLevel(TreeNode root, TreeNode currParent, int currLevel, int x, int y, int[] parents,
21+
int[] levels) {
22+
23+
if (root == null) {
24+
return;
25+
}
26+
27+
if (root.val == x) {
28+
parents[0] = currParent.val;
29+
levels[0] = currLevel;
30+
}
31+
32+
if (root.val == y) {
33+
parents[1] = currParent.val;
34+
levels[1] = currLevel;
35+
}
36+
37+
findParentAndLevel(root.left, root, currLevel + 1, x, y, parents, levels);
38+
findParentAndLevel(root.right, root, currLevel + 1, x, y, parents, levels);
39+
return;
40+
}
41+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy