forked from VibhutiJindal/CodeChef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA_BinaryTree
56 lines (49 loc) · 1.15 KB
/
LCA_BinaryTree
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
class Solution
{
public:
TreeNode *temp = new TreeNode();
bool getPath(TreeNode *root, vector<int> &arr, int x)
{
if (root == NULL)
return false;
arr.push_back(root->val);
if (root->val == x)
{
return true;
}
if (getPath(root->left, arr, x) || getPath(root->right, arr, x))
return true;
arr.pop_back();
return false;
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
vector<int> arrp;
getPath(root, arrp, p->val);
for (int i = 0; i < arrp.size(); i++)
{
cout << arrp[i];
}
cout << endl;
vector<int> arrq;
getPath(root, arrq, q->val);
for (int i = 0; i < arrq.size(); i++)
{
cout << arrq[i];
}
int n = min(arrp.size(), arrq.size());
for (int i = 0; i < n; i++)
{
if (arrp[i] != arrq[i])
{
break;
}
else
{
temp->val = arrp[i];
}
}
return temp;
;
}
};