fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5.  
  6. struct TreeNode{
  7. int val;
  8. TreeNode* left;
  9. TreeNode* right;
  10.  
  11. TreeNode(int val):val(val),left(nullptr),right(nullptr){};
  12. };
  13.  
  14. bool sum(TreeNode* root){
  15. if(!root)return true;
  16.  
  17. if(!root->left && !root->right)return true;
  18.  
  19. int left = root->left? root->left->val : 0;
  20. int right = root->right? root->right->val : 0;
  21.  
  22. return (root->val == left+right)&&sum(root->left)&&sum(root->right);
  23. }
  24. TreeNode* buildTree(){
  25. int x; cin>>x;
  26. if(x == -1)return nullptr;;
  27.  
  28. TreeNode* root = new TreeNode(x);
  29. queue<TreeNode*>q;
  30. q.push(root);
  31.  
  32. while(!q.empty()){
  33. auto u = q.front();
  34. q.pop();
  35.  
  36. if(cin>>x && x!=-1){
  37. u->left = new TreeNode(x);
  38. q.push(u->left);
  39. }
  40.  
  41. if(cin>>x && x!=-1){
  42. u->right = new TreeNode(x);
  43. q.push(u->right);
  44. }
  45. }
  46. return root;
  47. }
  48. int main() {
  49. TreeNode* root = buildTree();
  50. bool ans = sum(root);
  51. cout<<ans<<endl;
  52. return 0;
  53. }
Success #stdin #stdout 0s 5324KB
stdin
1 4 3 5
stdout
0