Last active
June 16, 2021 04:45
-
-
Save ForgottenProgramme/274f9ac29faa6eb20da04db0816822e0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Mahe Iram Khan | |
// 18 COB 058 | |
// GI 2028 | |
// Cousins of a node in a given binary tree | |
// Cousins are defined as children of a sibling node | |
#include <bits/stdc++.h> | |
using namespace std; | |
// Node struct | |
struct Node | |
{ | |
int data; | |
Node *left, *right; | |
}; | |
// newnode function | |
Node *newNode(int newitem) | |
{ | |
Node *temp = new Node; | |
temp->data = newitem; | |
temp->left = temp->right = NULL; | |
return temp; | |
} | |
// function to determine level of a node | |
int Level(Node *root, Node *node, int level) | |
{ | |
// base cases | |
if (root == NULL) | |
return 0; | |
if (root == node) | |
return level; | |
// node in left subtree | |
int downlevel = Level(root->left, node, level + 1); | |
if (downlevel != 0) | |
return downlevel; | |
// node not in left subtree | |
return Level(root->right, node, level + 1); | |
} | |
//print node, not sibling | |
void printLevel(Node* root, Node *node, int level) | |
{ | |
if (root == NULL || level < 2) | |
return; | |
if (level == 2) | |
{ | |
if (root->left == node || root->right == node) | |
return; | |
if (root->left) | |
cout << root->left->data << " "; | |
if (root->right) | |
cout << root->right->data; | |
} | |
else if (level > 2) | |
{ | |
printLevel(root->left, node, level - 1); | |
printLevel(root->right, node, level - 1); | |
} | |
} | |
// print cousins | |
void printCousins(Node *root, Node *node) | |
{ | |
int level = Level(root, node, 1); | |
printLevel(root, node, level); | |
} | |
int main() | |
{ int size; | |
cout<< "Enter number of nodes in tree."; | |
cin>>size; | |
cout<<"Enter the nodes of the tree. Press enter between two nodes."; | |
vector<int> input(size); | |
for(int i=0;i<size;i++){ | |
int val; | |
cin>>val; | |
input.push_back(val); | |
} | |
Node *root = newNode(input[1]); | |
root->left = newNode(input[2]); | |
root->right = newNode(input[3]); | |
root->left->left = newNode(input[4]); | |
root->left->right = newNode(input[5]); | |
root->left->right->right = newNode(input[6]); | |
root->right->left = newNode(input[7]); | |
root->right->right = newNode(input[8]); | |
root->right->left->right = newNode(input[9]); | |
printCousins(root, root->left->right); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment