forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03.04.2024.cpp
48 lines (40 loc) · 1.09 KB
/
03.04.2024.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
//User function Template for C++
/*// A Tree node
struct Node
{
int data;
struct Node *left, *right;
};*/
class Solution
{
public:
Node* LCA(Node* root, int x, int y){
if(!root) return NULL;
if(root->data==x || root->data==y) return root;
else if(root->data<x && root->data<y) return LCA(root->right, x,y);
else if(root->data>x && root->data>y) return LCA(root->left, x, y);
else{
return root;
}
}
void f(Node* root, Node* lca, vector<int>&path){
path.push_back(root->data);
if(root->data==lca->data) return;
else if(root->data > lca->data) f(root->left, lca, path);
else{
f(root->right, lca, path);
}
return;
}
/*You are required to complete below function */
int kthCommonAncestor(Node *root, int k,int x, int y)
{
// your code goes here
Node* lca=LCA(root, x, y);
vector<int>path;
f(root, lca, path);
int n=path.size();
if(path.size()<k) return -1;
return path[n-k];
}
};