fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class node{
  4. public:
  5. int data;
  6. node *left, *right;
  7. node(int data__){
  8. data = data__;
  9. left = right = NULL;
  10. }
  11. };
  12. node* make_tree(vector<int>& v){
  13. node *head = NULL, *ptr = NULL;
  14. int n = v.size();
  15. /*for(int i = 0; i < n; i++){
  16.   cout << v[i] << " ";
  17.   }*/
  18. if(n == 0){
  19. return NULL;
  20. }
  21. queue<node*> q;
  22. head = new node(v[0]);
  23. q.push(head);
  24. int i = 1;
  25. while(!q.empty() and i < n){
  26. node* x = q.front();
  27. q.pop();
  28. x -> left = new node(v[i++]);
  29. if(i < n){
  30. x -> right = new node(v[i++]);
  31. //i++;
  32. }
  33. q.push(x -> left);
  34. q.push(x -> right);
  35. }
  36. return head;
  37. }
  38. int sum(node* root){
  39. if(root == NULL){
  40. return 0;
  41. }
  42. return root -> data + sum(root -> left) + sum(root -> right);
  43. }
  44. int sumk(node *root, int k){
  45. if(root == NULL)
  46. return 0;
  47. int ans = 0;
  48. if(sum(root) == k){
  49. ans = 1;
  50. }
  51. int x = sumk(root -> left, k);
  52. int y = sumk(root -> right, k);
  53. return ans + x + y;
  54. }
  55. int main(){
  56. int t;
  57. cin >> t;
  58. while(t--){
  59. string ss, x;
  60. cin.ignore();
  61. getline(cin, ss);
  62. stringstream s(ss);
  63. vector<int> v;
  64. while(s >> x){
  65. //cout << x << ",";
  66. v.push_back(stoi(x));
  67. }
  68. node* root = make_tree(v);
  69. int k;
  70. cin >> k;
  71. int y = sumk(root, k);
  72. cout << y ;
  73. }
  74. return 0;
  75. }
Success #stdin #stdout 0s 4512KB
stdin
Standard input is empty
stdout
Standard output is empty