jain12

check existence of a path having given sum

Mar 18th, 2020
92
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. #include<vector>
  3. using namespace std;
  4.  
  5. class Node{
  6.   public:
  7.       int data;
  8.       Node *left,*right;
  9.       Node(int key){
  10.         data=key;
  11.         left=NULL;
  12.         right=NULL;
  13.         }
  14.   };
  15.  
  16. int CheckExistence(Node* root,int sum){
  17.   if(root==NULL)
  18.     return 0;
  19.   sum=sum-root->data;
  20.   if(sum>0)
  21.     return CheckExistence(root->left,sum)||CheckExistence(root->right,sum);
  22.   if(sum)
  23.     return 0;
  24.   else
  25.     return 1;
  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(CheckExistence(root,9))
  37.   cout<<"yes";
  38.   else
  39.     cout<<"no";
  40.   return 0;
  41.   }
Add Comment
Please, Sign In to add comment