m2skills

ancestor cpp

May 16th, 2018
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. // program to print all the ancestors of a node in binary tree
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. // node class
  7. class node{
  8. public:
  9.     int data;
  10.     node* left;
  11.     node* right;
  12. };
  13.  
  14. // function that returns a pointer to new node
  15. node* createNode(int element){
  16.     node* temp = (node*) malloc(sizeof(node));
  17.     temp->data = element;
  18.     temp->left = NULL;
  19.     temp->right = NULL;
  20.     return temp;
  21. }
  22.  
  23. // function to print all the ancestors of a node
  24. bool ancestors(node* root, int target){
  25.     // if the current node is null then return false
  26.     if(root == NULL){
  27.         return false;
  28.     }
  29.     // if the current node is our target node then we return true
  30.     if(root->data == target){
  31.         return true;
  32.     }
  33.     // here we recursively check if the current node if the ancestor of the target node then we need to print it
  34.     // the target node might lie in the left or the right subtree
  35.     // thus we take or of the the returned boolean values
  36.     if(ancestors(root->left, target) || ancestors(root->right, target)){
  37.         cout<<root->data<<" ";
  38.         return true;
  39.     }
  40.  
  41.     return false;
  42. }
  43.  
  44. int main() {
  45.  
  46.     node* head = createNode(1);
  47.     head->left = createNode(2);
  48.     head->right = createNode(3);
  49.     head->left->left = createNode(4);
  50.     head->left->right = createNode(5);
  51.     head->right->right = createNode(6);
  52.     head->left->left->right = createNode(7);
  53.     head->right->right->left = createNode(8);
  54.     head->left->left->right->left = createNode(9);
  55.     head->left->left->right->left->left = createNode(10);
  56.     head->right->right->left->right = createNode(11);
  57.     cout<<"All ancestors of node 10 are : ";
  58.     ancestors(head, 10);
  59.     cout<<"\nAll ancestors of node 5 are : ";
  60.     ancestors(head, 5);
  61.     cout<<"\nAll ancestors of node 8 are : ";
  62.     ancestors(head, 8);
  63.  
  64. }
  65.  
  66. /*
  67.  
  68. All ancestors of node 10 are : 9 7 4 2 1
  69. All ancestors of node 5 are : 2 1
  70. All ancestors of node 8 are : 6 3 1
  71. Process finished with exit code 0
  72.  
  73. */
Add Comment
Please, Sign In to add comment