m2skills

LCA cpp

May 15th, 2018
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // node class
  5. class node{
  6. public:
  7.     int data;
  8.     node* left;
  9.     node* right;
  10. };
  11.  
  12. // function that returns a pointer to new node
  13. node* createNode(int element){
  14.     node* temp = (node*) malloc(sizeof(node));
  15.     temp->data = element;
  16.     temp->left = NULL;
  17.     temp->right = NULL;
  18.     return temp;
  19. }
  20.  
  21. node* least_common_ancestor(node* root, int n1, int n2){
  22.     if(root == NULL){
  23.         return root;
  24.     }
  25.  
  26.     if(root->data == n1 || root->data == n2){
  27.         return root;
  28.     }
  29.  
  30.     node* left = least_common_ancestor(root->left, n1, n2);
  31.     node* right = least_common_ancestor(root->right, n1, n2);
  32.  
  33.     if(left != NULL && right != NULL){
  34.         return root;
  35.     }
  36.  
  37.     if(left != NULL){
  38.         return least_common_ancestor(root->left, n1, n2);
  39.     }
  40.     return least_common_ancestor(root->right, n1, n2);
  41. }
  42.  
  43.  
  44. int main() {
  45.  
  46.     node* head = createNode(1);
  47.     head->left = createNode(2);
  48.     head->right = createNode(3);
  49.     head->left->left = createNode(4);
  50.     head->left->right = createNode(5);
  51.     head->right->right = createNode(6);
  52.     head->left->left->right = createNode(7);
  53.     head->right->right->left = createNode(8);
  54.     head->left->left->right->left = createNode(9);
  55.     head->left->left->right->left->left = createNode(10);
  56.     head->right->right->left->right = createNode(11);
  57.     cout<<"Least common Ancestor of nodes 6 and 10 is : "<<least_common_ancestor(head, 6, 10)->data<<endl;
  58.     cout<<"Least common Ancestor of nodes 4 and 5 is : "<<least_common_ancestor(head, 4, 5)->data<<endl;
  59.     cout<<"Least common Ancestor of nodes 5 and 10 is : "<<least_common_ancestor(head, 5, 10)->data<<endl;
  60.  
  61. }
  62.  
  63.  
  64.  
  65. /*
  66.  
  67. Least common Ancestor of nodes 6 and 10 is : 1
  68. Least common Ancestor of nodes 4 and 5 is : 2
  69. Least common Ancestor of nodes 5 and 10 is : 2
  70. Process finished with exit code 0
  71.  
  72. */
Add Comment
Please, Sign In to add comment