-
Notifications
You must be signed in to change notification settings - Fork 22
/
ancestors in a binary tree
53 lines (49 loc) · 1.13 KB
/
ancestors in a binary tree
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
/*
Given a Binary Tree and a target key, your task is to complete the function printAncestors() that prints all the ancestors of the key in
the given binary tree.
1
/ \
2 3
/ \
4 5
/
7
Key: 7
Ancestor: 4 2 1
Input:
The function takes 2 arguments as input, first the reference pointer to the root node of the binary tree and a integer value target. There
will be multiple test cases and for each test the function will be called seperately.
Output:
For each test print all the ancestors of the target vlue in the order of their hierarchy.
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
2
2
1 2 L 1 3 R
2
5
1 2 R 1 3 L 2 4 L 2 5 R 4 7 L
7
Ouput:
1
4 2 1
*/
bool printAllAncestors(struct Node *root, int key){
if(root == NULL) return false;
if(root->data == key) return true;
if(printAllAncestors(root->left,key) ||
printAllAncestors(root->right,key))
{
cout<<root->data<<" ";
return true;
}
return false;
}
bool printAncestors(struct Node *root, int target)
{
bool ans = printAllAncestors(root, target);
cout<<'\n';
}