fork download
  1. //
  2. // main.cpp
  3. // Ancestors of a node
  4. //
  5. // Created by Himanshu on 15/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <queue>
  10. using namespace std;
  11.  
  12. struct node {
  13. int info = 0;
  14. struct node *left, *right;
  15. };
  16. typedef struct node Node;
  17.  
  18. node* newNode(int data)
  19. {
  20. node* Node = new node();
  21. Node->info = data;
  22. Node->left = NULL;
  23. Node->right = NULL;
  24.  
  25. return(Node);
  26. }
  27.  
  28.  
  29. bool ancestor (Node *root, int key) {
  30. if (!root) {
  31. return false;
  32. } else if (root->info == key) {
  33. return true;
  34. }
  35.  
  36. if ((ancestor (root->left, key)) || (ancestor (root->right, key))) {
  37. cout<<(root->info)<<" ";
  38. return true;
  39. }
  40.  
  41. return false;
  42. }
  43.  
  44.  
  45. int main() {
  46. Node *root = newNode(1);
  47. root->left = newNode(20);
  48. root->right = newNode(21);
  49. root->right->left = newNode(30);
  50. root->right->right = newNode(31);
  51. root->right->right->left = newNode(40);
  52. root->right->right->left->right = newNode(51);
  53.  
  54. cout<<"The ancestors of 30 are: "<<endl;
  55. ancestor(root, 30);
  56. cout<<endl;
  57.  
  58. cout<<"The ancestors of 51 are: "<<endl;
  59. ancestor(root, 51);
  60. cout<<endl;
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0.01s 5460KB
stdin
Standard input is empty
stdout
The ancestors of 30 are: 
21 1 
The ancestors of 51 are: 
40 31 21 1