//
// 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;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBMb3dlc3QgQ29tbW9uIEFuY2VzdG9yIChMQ0EpCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDMxLzEwLzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8cXVldWU+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpzdHJ1Y3Qgbm9kZSB7CiAgICBpbnQgaW5mbyA9IDA7CiAgICBzdHJ1Y3Qgbm9kZSAqbGVmdCwgKnJpZ2h0Owp9Owp0eXBlZGVmIHN0cnVjdCBub2RlIE5vZGU7Cgpub2RlKiBuZXdOb2RlKGludCBkYXRhKQp7CiAgICBub2RlKiBOb2RlID0gbmV3IG5vZGUoKTsKICAgIE5vZGUtPmluZm8gPSBkYXRhOwogICAgTm9kZS0+bGVmdCA9IE5VTEw7CiAgICBOb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