Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to find out if 2 nodes are cousins or not
- #include <iostream>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to find and return the level of a node in binary tree
- int level_of_node(node* root, int data, int level = -1){
- // if the tree is empty or if we reach a leaf node then return 0
- if (root == NULL){
- return -1;
- }
- if(root->data == data){
- return level+1;
- }
- // check in the left subtree for the element
- // if found then return the level
- int level_node = level_of_node(root->left, data, level + 1);
- if (level_node != -1){
- return level_node;
- }
- // searching for the node in right subtree
- level_node = level_of_node(root->right, data, level + 1);
- return level_node;
- }
- // function to check if 2 nodes are siblings or not
- bool isSibling(node* parent, int n1, int n2){
- if(parent == NULL){
- return false;
- }
- if(parent->left != NULL && parent->right != NULL) {
- return (parent->left->data == n1 && parent->right->data == n2) ||
- (parent->left->data == n2 && parent->right->data == n1);
- }
- return (isSibling(parent->left, n1, n2) ||
- isSibling(parent->right, n1, n2)
- );
- }
- bool isCousin(node* root, int a, int b){
- if( (level_of_node(root, a) == level_of_node(root, b) && isSibling(root, a, b))){
- return true;
- }
- return false;
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- cout<<"Nodes 2 and 3 are siblings : "<<isCousin(head, 2, 3)<<endl;
- cout<<"Nodes 6 and 10 are siblings : "<<isCousin(head, 6, 10)<<endl;
- cout<<"Nodes 7 and 8 are siblings : "<<isCousin(head, 7, 8)<<endl;
- }
- /*
- Nodes 2 and 3 are siblings : 1
- Nodes 6 and 10 are siblings : 0
- Nodes 7 and 8 are siblings : 0
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment