forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth Ancestor of a node in Binary tree.cpp
75 lines (62 loc) · 1.45 KB
/
kth Ancestor of a node in Binary tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* C++ program to calculate Kth ancestor of given node */
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// temporary node to keep track of Node returned
// from previous recursive call during backtrack
Node* temp = NULL;
// recursive function to calculate Kth ancestor
Node* kthAncestorDFS(Node *root, int node , int &k)
{
// Base case
if (!root)
return NULL;
if (root->data == node||
(temp = kthAncestorDFS(root->left,node,k)) ||
(temp = kthAncestorDFS(root->right,node,k)))
{
if (k > 0)
k--;
else if (k == 0)
{
// print the kth ancestor
cout<<"Kth ancestor is: "<<root->data;
// return NULL to stop further backtracking
return NULL;
}
// return current node to previous call
return root;
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
int k = 2;
int node = 5;
// print kth ancestor of given node
Node* parent = kthAncestorDFS(root,node,k);
// check if parent is not NULL, it means
// there is no Kth ancestor of the node
if (parent)
cout << "-1";
return 0;
}