Skip to content

Commit

Permalink
Create 03.04.2024.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Masked-coder11 authored Apr 3, 2024
1 parent 0da94af commit 5823951
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 03.04.2024.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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];
}
};

0 comments on commit 5823951

Please sign in to comment.