-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfirst_common_ancestor.cpp
58 lines (52 loc) · 1.34 KB
/
first_common_ancestor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//https://ide.geeksforgeeks.org/KXWdLMTV8d
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
Node *newNode(int data){
Node *curr = new Node();
curr->data = data;
curr->left = curr->right = NULL;
return curr;
}
Node *findLCAUtil(Node *root,int n1,int n2,bool &v1,bool &v2){
if(root == NULL)return NULL;
if(root->data == n1){
v1 = true;
return root;
}
if(root->data == n2){
v2 = true;
return root;
}
Node *lca = findLCAUtil(root->left,n1,n2,v1,v2);
Node *rca = findLCAUtil(root->right,n1,n2,v1,v2);
if(lca && rca)return root;
return(lca!=NULL)?lca:rca;
}
bool find(Node *root, int k){
if(root == NULL) return NULL;
if(root->data == k) return root;
if(find(root->left, k) || find(root->right, k)) return true;
return false;
}
Node* LCA(Node *root, int n1, int n2){
if(root == NULL) return NULL;
bool v1, v2;
Node* res = findLCAUtil(root, n1, n2, v1, v2);
if(v1 && v2 || v1 && find(res, v2) || v2 && find(res, v1))
return res;
else
return NULL;
}
int main(){
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout<<LCA(root, 4, 5)->data<<"\n";