Skip to content

Commit 4509a04

Browse files
authored
Create 2nd Approach.cpp
1 parent b76ad4e commit 4509a04

File tree

1 file changed

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

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
bool solve(Node* root, int k, int node, vector<int> &ans){
2+
if(root == NULL) return false;
3+
4+
ans.push_back(root -> data);
5+
6+
if(root -> data == node) return true;
7+
8+
9+
if(solve(root -> left, k, node, ans) || solve(root -> right, k, node, ans)) return true;
10+
11+
ans.pop_back();
12+
13+
return false;
14+
}
15+
16+
int kthAncestor(Node *root, int k, int node)
17+
{
18+
vector<int> ans;
19+
if(!solve(root, k, node, ans)) return -1;
20+
21+
int ancestorIndex = ans.size() - k - 1;
22+
if(ancestorIndex < 0) return -1;
23+
24+
return ans[ancestorIndex];
25+
}

0 commit comments

Comments
 (0)