-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathLCAinBST.cpp
42 lines (39 loc) · 926 Bytes
/
LCAinBST.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
struct Node
{
int data;
struct Node*left;
struct Node*right;
Node(int x){
data=x;
left=right=NULL;
}
};
class Solution
{
public:
//Function to return the lowest common ancestor in a Binary Tree.
Node* lca(Node* root ,int n1 ,int n2 )
{
//Your code here
if(root==NULL){
return NULL;
}
if(root->data==n1 || root->data==n2){
return root;
}
Node*leftAns=lca(root->left,n1,n2);
Node*rightAns=lca(root->right,n1,n2);
if(leftAns==NULL && rightAns==NULL){
return NULL;
}
else if(leftAns!=NULL && rightAns==NULL){
return leftAns;
}
else if(leftAns==NULL && rightAns!=NULL){
return rightAns;
}
else if(leftAns!=NULL && rightAns!=NULL){
return root;
}
}
};