//
//  main.cpp
//  Lowest Common Ancestor (LCA)
//
//  Created by Himanshu on 31/10/21.
//

#include <iostream>
#include <queue>
using namespace std;

struct node {
    int info = 0;
    struct node *left, *right;
};
typedef struct node Node;

node* newNode(int data)
{
    node* Node = new node();
    Node->info = data;
    Node->left = NULL;
    Node->right = NULL;
 
    return(Node);
}


Node* lca (Node *root, int n1, int n2) {
    if (root == NULL) {
        return NULL;
    }
    
    if (root->info == n1 || root->info == n2) {
        return root;
    }
    
    Node *leftLCA  = lca(root->left, n1, n2);
    Node *rightLCA = lca(root->right, n1, n2);
    
    if (leftLCA && rightLCA) {
        return root;
    }
   
    return (leftLCA != NULL)? leftLCA : rightLCA;
}


int main() {
    Node *root = newNode(1);
    root->left = newNode(20);
    root->right = newNode(21);
    root->right->left = newNode(30);
    root->right->right = newNode(31);
    root->right->right->left = newNode(40);
    root->right->right->left->right = newNode(51);
    
    Node *key = NULL;

    cout<<"The lowest common ancestors of 20 amd 30 are: "<<endl;
    key = lca(root, 20, 30);
    cout<<(key->info);
    cout<<endl;
    
    cout<<"The lowest common ancestors of 40 amd 51 are: "<<endl;
    key = lca(root, 40, 51);
    cout<<(key->info);
    cout<<endl;

    return 0;
}
