Created
November 12, 2016 22:08
-
-
Save sachin-kmr/121f3073738488ed933214fa252bc8d1 to your computer and use it in GitHub Desktop.
Program to Print data of GrandParent of a given node in BST
This file contains 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
// Ques : Write a program to Print data of GrandParent of a given node in Binary Search Tree | |
// Created By : Sachin Kumar | |
// College : Sophomore, NSIT, Delhi | |
#include <iostream> | |
#include <cstdlib> | |
using namespace std; | |
struct Node{ | |
int data; | |
Node *left, *right; | |
}; | |
Node *parent = NULL, *grandparent = NULL, *current = NULL; | |
void Insert(Node **root, int element){ | |
if(*root == NULL){ | |
Node *temp = new Node; | |
temp->right = temp->left = NULL; | |
temp->data = element; | |
*root = temp; | |
return; | |
} | |
if((*root)->data > element){ | |
Insert(&(*root)->left, element); | |
} | |
else{ | |
Insert(&(*root)->right, element); | |
} | |
} | |
void Inorder(Node *root){ | |
if(root==NULL){ | |
return; | |
} | |
Inorder(root->left); | |
cout << root->data << " "; | |
Inorder(root->right); | |
} | |
void Find(Node *root, int element, int c){ | |
if(root == NULL){ | |
return; | |
} | |
if(c==0){ | |
current = root; | |
grandparent = NULL; | |
parent = NULL; | |
}else if(c==1){ | |
grandparent = NULL; | |
parent = current; | |
current = root; | |
} | |
else{ | |
grandparent = parent; | |
parent = current; | |
current = root; | |
} | |
if(root->data == element){ | |
return; | |
} | |
if(root->data > element){ | |
Find(root->left, element, c+1); | |
} | |
else if(root->data < element){ | |
Find(root->right, element, c+1); | |
} | |
} | |
int main(){ | |
int element, temp; | |
Node *root = NULL; | |
cout << endl << "Lets Begin!" << endl << endl; | |
while(1){ | |
cout << "Enter operation you want : \n 1. Insert \n 2. Print \n 3. Find Grandparent \n 4. Exit \n"; | |
cin >> temp; | |
switch(temp){ | |
case 1: | |
cout << "Enter element : "; | |
cin >> element; | |
Insert(&root, element); | |
break; | |
case 2: | |
cout << "Tree is : "; | |
Inorder(root); | |
cout << endl << endl; | |
break; | |
case 3: | |
cout << "Enter element whose grandparent to find : "; | |
cin >> element; | |
cout << endl; | |
Find(root, element, 0); | |
if(grandparent == NULL){ | |
cout << "Error" << endl << endl; | |
}else | |
cout << "Grandparent is : " << grandparent->data << endl << endl; | |
break; | |
case 4: | |
exit(0); | |
default: | |
cout << "Wrong operation selected" << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment