Sanath12345

Untitled

May 21st, 2021
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. struct bnode {
  4. int data;
  5. struct bnode *l,*r;
  6. bnode(int data)
  7. {
  8. this->data = data;
  9. l = r = NULL;
  10. }
  11. };
  12. void getparent(struct bnode *T,int x,int &p){
  13. if(T==NULL) return;
  14. if(T->l!=NULL and T->l->data==x){
  15. p=T->data;
  16. return ;
  17. }
  18. if(T->r!=NULL and T->r->data==x){
  19. p=T->data;
  20. return ;
  21. }
  22. getparent(T->l,x,p);
  23. getparent(T->r,x,p);
  24. }
  25. bnode* get_sibling(bnode *node, int key)
  26. {
  27. if (node == NULL || node->data == key)
  28. {
  29. return NULL;
  30. }
  31.  
  32. if (node->l != NULL && node->l->data == key)
  33. {
  34. return node->r;
  35. }
  36.  
  37. if (node->r != NULL && node->r->data == key)
  38. {
  39. return node->l;
  40. }
  41.  
  42. bnode *temp = get_sibling(node->l, key);
  43.  
  44. if (temp != NULL)
  45. {
  46. return temp;
  47. }
  48.  
  49. temp = get_sibling(node->r, key);
  50. return temp;
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56.  
  57. struct bnode* root = new bnode(4);
  58. root->l = new bnode(3);
  59. root->r = new bnode(9);
  60. root->l->l = new bnode(5);
  61. root->l->r = new bnode(6);
  62. root->r->l = new bnode(1);
  63. root->r->r = new bnode(8);
  64. int node,p;
  65. cout<<"enter node value : "<<endl;
  66. cin>>node;
  67. getparent(root,node,p);
  68. bnode *sibling = get_sibling(root,p);
  69. if (sibling != NULL)
  70. {
  71. cout<<"The uncle of "<<node<<" is " << sibling->data<<endl;
  72. } else {
  73. cout<<-1<<endl;
  74. }
  75.  
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment