File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
17 - Binary Tree Data Structure Problems/28 - Kth Ancestor in a Tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments