Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct bnode {
- int data;
- struct bnode *l,*r;
- bnode(int data)
- {
- this->data = data;
- l = r = NULL;
- }
- };
- void getparent(struct bnode *T,int x,int &p){
- if(T==NULL) return;
- if(T->l!=NULL and T->l->data==x){
- p=T->data;
- return ;
- }
- if(T->r!=NULL and T->r->data==x){
- p=T->data;
- return ;
- }
- getparent(T->l,x,p);
- getparent(T->r,x,p);
- }
- bnode* get_sibling(bnode *node, int key)
- {
- if (node == NULL || node->data == key)
- {
- return NULL;
- }
- if (node->l != NULL && node->l->data == key)
- {
- return node->r;
- }
- if (node->r != NULL && node->r->data == key)
- {
- return node->l;
- }
- bnode *temp = get_sibling(node->l, key);
- if (temp != NULL)
- {
- return temp;
- }
- temp = get_sibling(node->r, key);
- return temp;
- }
- int main()
- {
- struct bnode* root = new bnode(4);
- root->l = new bnode(3);
- root->r = new bnode(9);
- root->l->l = new bnode(5);
- root->l->r = new bnode(6);
- root->r->l = new bnode(1);
- root->r->r = new bnode(8);
- int node,p;
- cout<<"enter node value : "<<endl;
- cin>>node;
- getparent(root,node,p);
- bnode *sibling = get_sibling(root,p);
- if (sibling != NULL)
- {
- cout<<"The uncle of "<<node<<" is " << sibling->data<<endl;
- } else {
- cout<<-1<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment