Skip to content

Commit 16f720a

Browse files
committed
993. Cousins in Binary Tree
1 parent c162b15 commit 16f720a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

cousins-in-binary-tree.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Runtime: 8 ms
2+
// Memory Usage: 11.9 MB
3+
class Solution {
4+
public:
5+
6+
TreeNode* findParent(TreeNode* root, int d, int val, int &depth) {
7+
if (!root) return NULL;
8+
9+
if (root->left && root->left->val == val) {
10+
depth = d;
11+
return root;
12+
}
13+
14+
if (root->right && root->right->val == val) {
15+
depth = d;
16+
return root;
17+
}
18+
19+
TreeNode* l = findParent(root->left, d + 1, val, depth);
20+
if (l != NULL) {
21+
return l;
22+
}
23+
24+
return findParent(root->right, d + 1, val, depth);
25+
}
26+
27+
bool isCousins(TreeNode* root, int x, int y) {
28+
int xd = -1;
29+
int yd = -1;
30+
TreeNode* lp = findParent(root, 0, x, xd);
31+
TreeNode* rp = findParent(root, 0, y, yd);
32+
return lp != rp && xd == yd;
33+
}
34+
};

0 commit comments

Comments
 (0)