-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCousins in Binary Tree.cpp
More file actions
55 lines (52 loc) · 1.35 KB
/
Cousins in Binary Tree.cpp
File metadata and controls
55 lines (52 loc) · 1.35 KB
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<int> Solution::solve(TreeNode* root, int k) {
queue<pair<TreeNode*,TreeNode*>> q;
q.push({root,NULL});
vector<int> ans;
while(!q.empty())
{
int size=q.size();
vector<pair<int,TreeNode*>> temp;
TreeNode* parent=NULL;
bool flag=false;
while(size--)
{
TreeNode* node=q.front().first;
TreeNode* par=q.front().second; // "par" is parent of every node.
q.pop();
if(node->val==k)
{
flag=true;
parent=par; // "parent" is parent of targeted node
}
temp.push_back({node->val,par});
if(node->left)
{
q.push({node->left,node});
}
if(node->right)
{
q.push({node->right,node});
}
}
if(flag)
{
for(auto x: temp)
{
// checking for different parent in same level of binary tree.
if(x.second!=parent)
ans.push_back(x.first);
}
break;
}
}
return ans;
}