Skip to content

Commit 53887f7

Browse files
authored
Create main.cpp
1 parent 24b13e3 commit 53887f7

File tree

1 file changed

+38
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/28 - Kth Ancestor in a Tree

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Node* solve(Node* root, int& k, int node){
2+
if(root == NULL) return NULL;
3+
4+
if(root -> data == node) return root;
5+
6+
Node* leftAns = solve(root -> left, k, node);
7+
Node* rightAns = solve(root -> right, k, node);
8+
9+
if(leftAns != NULL && rightAns == NULL){
10+
k--;
11+
if(k <= 0) {
12+
k = INT_MAX;
13+
return root;
14+
}
15+
16+
return leftAns;
17+
}
18+
19+
if(leftAns == NULL && rightAns != NULL){
20+
k--;
21+
if(k <= 0) {
22+
k = INT_MAX;
23+
return root;
24+
}
25+
26+
return rightAns;
27+
}
28+
29+
return NULL;
30+
}
31+
32+
int kthAncestor(Node *root, int k, int node)
33+
{
34+
Node* ancestor = solve(root, k, node);
35+
if(ancestor == NULL || ancestor -> data == node) return -1;
36+
37+
return ancestor->data;
38+
}

0 commit comments

Comments
 (0)