fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node *left;
  8. struct node *right;
  9. };
  10. struct node * newnode(int x)
  11. {
  12. struct node *temp=new node;
  13. temp->data=x;
  14. temp->left=NULL;
  15. temp->right=NULL;
  16. return temp;
  17. }
  18.  
  19. //vector<int> v;
  20.  
  21. int haspath(struct node* root,int sum,int level,int *count)
  22. {
  23. //v.push_back(root->data);
  24. int flag=0;
  25. if(root==NULL)
  26. {
  27. if(sum==0)
  28. {
  29. *count=(*count)+1;
  30. cout<<count<<endl;
  31. // for(int i=0;i<v.size();i++)
  32. // {
  33. // cout<<v[i];
  34. // }
  35.  
  36. return 1;
  37. }
  38. return 0;
  39. }
  40.  
  41.  
  42.  
  43. flag=haspath(root->left,sum-root->data,level+1,count) || flag;
  44. flag=haspath(root->right,sum-root->data,level+1,count) || flag;
  45.  
  46. return flag;
  47.  
  48.  
  49. }
  50.  
  51.  
  52. int main() {
  53.  
  54. struct node* root = newnode(1);
  55. root->left = newnode(10);
  56. root->right = newnode(15);
  57. root->left->left = newnode(5);
  58. root->left->right = newnode(2);
  59.  
  60. int sum=16;
  61. int level=0;
  62. int count=0;
  63. int ans= haspath(root,sum,level,&count);
  64. cout<<ans<<endl;
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
0x7ffdbc923a0c
0x7ffdbc923a0c
0x7ffdbc923a0c
0x7ffdbc923a0c
1