forked from TECHOUS/DSKaKhel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintCousins.cpp
More file actions
81 lines (60 loc) · 1.72 KB
/
PrintCousins.cpp
File metadata and controls
81 lines (60 loc) · 1.72 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<iostream>
#include<stdlib.h>
#include<bits/stdc++.h>
#include<queue>
using namespace std;
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node *newNode(int data){
struct Node *temp = (struct Node *) malloc (sizeof(struct Node));
temp -> data = data;
temp -> left = NULL;
temp -> right = NULL;
return temp;
}
/*
1
/ \
2 3
/ \ /
4 5 6
/
7
1 2 3 4 5 6
if key == 6
1 2 3 is ignored as its their root or parents and semi parent;
4 5 is the cousin as 6 isnt present in its parent node.
ignore 6 as its the key
*/
void findCousins(struct Node *root,int key){
struct Node *first = root;
struct Node *second = root;
if(root == NULL){
return ;
}
if(root->data == key || (root->left->data == key || root->right->data == key)){
cout<<"-1"<<endl;
}
else{
if(root->right->left->data == key){
printf("%d",root->left->left->data);
printf("%d",root->left->right->data);
}
}
findCousins(root->left,key);
findCousins(root->right,key);
}
int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->left->right = newNode(7);
findCousins(root,4);
}