-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7. Cousins in Binary Tree.cpp
66 lines (53 loc) · 1.76 KB
/
7. 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
*/
/**
* 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:
//n finding node ; h current depth ; d depth of finding node
TreeNode* depth(TreeNode* root, int& n, int h, int& d )
{
if(root==NULL) return NULL;
//left children
if(root->left && root->left->val==n)
{
d=h+1;
return root;
}
//right children
if(root->right && root->right->val==n)
{
d=h+1;
return root;
}
//if not found, move down the tree
TreeNode* l = depth(root->left,n,h+1,d);
if(l) return l;
TreeNode* r = depth(root->right,n,h+1,d);
if(r) return r;
return NULL;
}
bool isCousins(TreeNode* root, int x, int y)
{
int xDepth=-1, yDepth=-1;
TreeNode* xParent = depth(root,x,0,xDepth);
TreeNode* yParent = depth(root,y,0,yDepth);
if(xParent!=yParent && xDepth==yDepth)
return true;
else
return false;
}
};