Skip to content

Commit 89d5c3c

Browse files
Added solutio
1 parent 7102feb commit 89d5c3c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

cousins_binary_tree.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int parent_x = -1, parent_y = -1, depth_x = -1, depth_y = -1, x, y;
13+
14+
void findDepthAndCheckParent(TreeNode* root, int depth) {
15+
if(root == NULL) return;
16+
if(root->left && root->left->val == x || root->right && root->right->val == x) parent_x = root->val;
17+
18+
if(root->left && root->left->val == y || root->right && root->right->val == y) parent_y = root->val;
19+
if(root->val == x) depth_x = depth;
20+
if(root->val == y) depth_y = depth;
21+
22+
findDepthAndCheckParent(root->left, depth + 1);
23+
findDepthAndCheckParent(root->right, depth + 1);
24+
}
25+
26+
bool isCousins(TreeNode* root, int x, int y) {
27+
if(root == NULL) return false;
28+
this->x = x, this->y = y;
29+
findDepthAndCheckParent(root, 0);
30+
return (depth_x == depth_y) && (parent_x != parent_y);
31+
32+
}
33+
};

0 commit comments

Comments
 (0)