Skip to content

Commit 8b4d924

Browse files
Merge pull request #161 from FazeelUsmani/cousins-in-BT
Create 18_cousinsInBT.cpp
2 parents 0a9f97d + 1049041 commit 8b4d924

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
void rec(TreeNode* root, int x, int y, int d, int parent) {
4+
if (!root) return;
5+
6+
if (root->val == x) dx = d, x_par = parent;
7+
if (root->val == y) dy = d, y_par = parent;
8+
9+
if (dx != -1 && dy != -1) return;
10+
11+
rec(root->left, x, y, d+1, root->val);
12+
rec(root->right, x, y, d+1, root->val);
13+
}
14+
bool isCousins(TreeNode* root, int x, int y) {
15+
rec(root, x, y, 0, -1);
16+
return dx == dy && x_par != y_par;
17+
}
18+
19+
private:
20+
int dx = -1, dy = -1, x_par = -1, y_par = -1;
21+
};

0 commit comments

Comments
 (0)