993.Cousins in Binary Tree



Last updated



Last updated
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
pair<int,int>depth;
bool getDepth(TreeNode* root, int x)
{
if(root->left )
{
if(root->left->val == x){
++depth.first ;
depth.second=root->val;
return true;
}
else if(getDepth(root->left, x))
{
++depth.first ;
return true;
}
}
if(root->right)
{
if(root->right->val == x)
{
++depth.first ;
depth.second=root->val;
return true;
}
else if(getDepth(root->right, x))
{
++depth.first ;
return true;
}
}
return false;
}
public:
bool isCousins(TreeNode* root, int x, int y) {
if(root->val == x || root->val ==y) return false;
depth=pair<int,int>(0,0);
getDepth(root,x);
pair<int,int>xp(depth);
depth.first=0;
getDepth(root,y);
// cout<<xp.first << " "<< xp.second<<endl;
// cout<<depth.first << " "<< depth.second<<endl;
return xp.first==depth.first && xp.second != depth.second;
}
};