-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA Of Binary Tree
41 lines (33 loc) · 884 Bytes
/
LCA Of Binary Tree
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
#include <bits/stdc++.h>
/************************************************************
Following is the TreeNode class structure
template <typename T>
class TreeNode {
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
};
************************************************************/
TreeNode<int>* LCA(TreeNode<int>* node, int x, int y)
{
if(!node || node->data==x || node->data==y)
{
return node;
}
TreeNode<int>* l=LCA(node->left,x,y);
TreeNode<int>* r=LCA(node->right,x,y);
if(!r) return l;
else if(!l) return r;
else return node;
}
int lowestCommonAncestor(TreeNode<int> *root, int x, int y)
{
TreeNode<int>* node = LCA(root,x,y);
return node->data;
}