Skip to content

Commit 57d7cdd

Browse files
authored
Create main.cpp
1 parent a3e85c6 commit 57d7cdd

File tree

1 file changed

+19
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/25 - LCA in Binary Tree

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution
2+
{
3+
public:
4+
//Function to return the lowest common ancestor in a Binary Tree.
5+
Node* lca(Node* root ,int n1 ,int n2 )
6+
{
7+
if(root == NULL) return NULL;
8+
9+
if(root -> data == n1 || root -> data == n2) return root;
10+
11+
Node* leftAns = lca(root -> left, n1, n2);
12+
Node* rightAns = lca(root -> right, n1, n2);
13+
14+
if(leftAns != NULL && rightAns != NULL) return root;
15+
else if(leftAns != NULL && rightAns == NULL) return leftAns;
16+
else if(leftAns == NULL && rightAns != NULL) return rightAns;
17+
else return NULL;
18+
}
19+
};

0 commit comments

Comments
 (0)