Skip to content

Commit 62f83cd

Browse files
committed
Added solution - LeetHub
1 parent 2d71c8f commit 62f83cd

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

Kth Ancestor in a Tree - GFG/kth-ancestor-in-a-tree.cpp

+46-3
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,52 @@ void solve1(Node *root, int k, int node, int &ans, vector<int>v)
127127
solve1(root->left, k, node, ans, v);
128128
solve1(root->right, k, node, ans, v);
129129
}
130+
131+
Node* solve2(Node *root, int &k, int node)
132+
{
133+
if(!root)
134+
return NULL;
135+
136+
if(root->data == node)
137+
return root;
138+
139+
Node *leftAns = solve2(root->left, k, node);
140+
Node *rightAns = solve2(root->right, k, node);
141+
142+
if(leftAns!=NULL && rightAns==NULL)
143+
{
144+
k--;
145+
if(k <= 0)
146+
{
147+
148+
k=INT_MAX;
149+
return root;
150+
}
151+
return leftAns;
152+
}
153+
if(leftAns==NULL && rightAns!=NULL)
154+
{
155+
k--;
156+
if(k <= 0)
157+
{
158+
k=INT_MAX;
159+
return root;
160+
}
161+
return rightAns;
162+
}
163+
return NULL;
164+
}
165+
130166
int kthAncestor(Node *root, int k, int node)
131167
{
132-
int ans=-1;
133-
solve1(root, k, node, ans, {});
134-
return ans;
168+
// By Method-1
169+
// int ans=-1;
170+
// solve1(root, k, node, ans, {});
171+
// return ans;
172+
173+
// By Method-2
174+
Node* ans = solve2(root, k, node);
175+
if(ans == NULL || ans->data == node)
176+
return -1;
177+
return ans->data;
135178
}

0 commit comments

Comments
 (0)