Cousins in Binary Tree
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.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3 Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3 Output: false
Constraints:
- The number of nodes in the tree will be between
2
and100
. - Each node has a unique integer value from
1
to100
.
/**
* 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:
TreeNode* ht(TreeNode* root,int x,int &cnt)
{
if(root==NULL)return 0;
queue<TreeNode*> q;
int l=0;
q.push(root);
TreeNode* p1=NULL;
while(!q.empty())
{
int s=q.size();
int f=1;
while(s--)
{
if(f)
{
++cnt,f=0;
}
auto k=q.front();
q.pop();
if(k->left){
if(k->left->val==x)
{
p1=k;
l=1;
break;
}
q.push(k->left);
}
if(k->right){
if(k->right->val==x)
{
p1=k;
l=1;
break;
}
q.push(k->right);}
}
if(l)break;
}
return p1;
}
bool isCousins(TreeNode* root, int x, int y) {
int h1=0,h2=0;
TreeNode* p1=ht(root,x,h1);
// cout<<h1<<" "<<p1->val<<" -";
TreeNode* p2=ht(root,y,h2);
// cout<<h2<<" "<<p2->val;
if(h1==h2&&p1!=p2)
return true;
else
return false;
}
};