Adrita

task 6 (ds lab 7) 3rd sem

Aug 4th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node
  4. {
  5. int data;
  6. struct node* left;
  7. struct node* right;
  8. };
  9. typedef struct node Node;
  10. Node* create_node(int item)
  11. {
  12. Node* new_node=new Node();
  13. if(new_node==NULL)
  14. cout<<"Error"<<endl;
  15. else
  16. {
  17. new_node->data=item;
  18. new_node->left=new_node->right=NULL;
  19. }
  20. return new_node;
  21. }
  22. Node* insert_key(Node* x,int key)
  23. {
  24. Node* new_node=create_node(key);
  25. if(x==NULL)
  26. return new_node;
  27. if(key>x->data)
  28. x->right=insert_key(x->right,key);
  29. else if(key<x->data)
  30. x->left=insert_key(x->left,key);
  31. return x;
  32. }
  33. int maxpath(Node *q, int x)
  34. {
  35. Node *p=q;
  36. int mx=INT_MIN;
  37. while(p->data!=x)
  38. {
  39. if(p->data>x)
  40. {
  41. mx=max(mx,p->data);
  42. p=p->left;
  43. }
  44. else
  45. {
  46. mx=max(mx,p->data);
  47. p=p->right;
  48. }
  49. }
  50. return max(mx,x);
  51. }
  52. Node* lca(Node* root, int x, int y)
  53. {
  54. if(root == NULL)
  55. return NULL;
  56. if(root->data>x && root->data>y)
  57. return lca(root->left,x,y);
  58. if(root->data<x && root->data<y)
  59. return lca(root->right,x,y);
  60.  
  61. return root;
  62. }
  63. int maxelement(Node* root,int x,int y)
  64. {
  65. Node *p;
  66. p=lca(root,x,y);
  67. return max(maxpath(p,x),maxpath(p,y));
  68. }
  69. int main()
  70. {
  71. Node* root=NULL;
  72. while(1)
  73. {
  74. int n;
  75. cin>>n;
  76. if(n!=-1)
  77. root=insert_key(root,n);
  78. else
  79. break;
  80. }
  81. int n;
  82. cin>>n;
  83. while(n--)
  84. {
  85. int x,y;
  86. cin>>x>>y;
  87. cout<<maxelement(root,x,y)<<endl;
  88. }
  89. }
  90.  
  91.  
Advertisement
Add Comment
Please, Sign In to add comment