-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCousins_in_Binary_Tree.cpp
45 lines (45 loc) · 1.38 KB
/
Cousins_in_Binary_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int finddepth(TreeNode* root, int x){
if(root == NULL){
return 0;
}
if(root->val == x) return 1;
int l = finddepth(root->left,x);
int r = finddepth(root->right, x);
if(l +r) return l+r + 1;
return 0;
}
TreeNode* findparent(TreeNode* root,int x){
if(!root) return NULL;
if(root->val == x) return NULL;
if(root->left && root ->left->val == x) return root;
if(root->right && root->right->val == x) return root;
TreeNode* l = findparent(root->left,x);
TreeNode* r = findparent(root->right,x);
if(l) return l;
if(r) return r;
return NULL;
}
bool isCousins(TreeNode* root, int x, int y) {
int d1 = finddepth(root,x);
int d2 = finddepth(root,y);
if(d1 != d2) return false;
// cout<<d1<<" "<<d2<<" ";
TreeNode* p1 = findparent(root,x);
TreeNode* p2 = findparent(root,y);
if(p1 == p2) return false;
return true;
}
};