jain12

print ancestors of a given node in a binary tree (2)

Mar 22nd, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node{
  5.   public:
  6.       int data;
  7.       Node *left,*right;
  8.       Node(int key){
  9.         data=key;
  10.         left=NULL;
  11.         right=NULL;
  12.         }
  13.   };
  14.  
  15. int PrintAncestors(Node* root,int key){
  16.  if(root==NULL)
  17.     return 0;
  18.  if(root->data==key)
  19.     return 1;
  20.  if(PrintAncestors(root->left,key)||PrintAncestors(root->right,key)){
  21.      cout<<" "<<root->data;
  22.      return 1;
  23.      }
  24.  else
  25.      return 0;
  26.  }
  27.  
  28. int main(){
  29.   Node* root=NULL;
  30.   Node* newnode=new Node(1);
  31.   root=newnode;
  32.   root->left=new Node(9);
  33.   root->right=new Node(3);
  34.   (root->left)->left=new Node(2);
  35.   (root->right)->right=new Node(4);
  36.   if(!PrintAncestors(root,1))
  37.     cout<<"ancestors not found";
  38.   return 0;
  39.   }
Add Comment
Please, Sign In to add comment