Advertisement
Guest User

Equal Tree Partition

a guest
Jan 24th, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. /**
  2.  * Definition for binary tree
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10.  
  11. int preCalculate(TreeNode* V) {
  12.     int sum = V->val;
  13.     if (V->left) sum += preCalculate(V->left);
  14.     if (V->right) sum += preCalculate(V->right);
  15.     return sum;
  16. }
  17. int isPossible(TreeNode* V, int& total, int& possible) {
  18.     int sum = V->val;
  19.     if (V->left) sum += isPossible(V->left, total, possible);
  20.     if (V->right) sum += isPossible(V->right, total, possible);
  21.     if (2*sum == total) possible = 1;
  22.     return sum;
  23. }
  24. int Solution::solve(TreeNode* A) {
  25.     int sum = preCalculate(A), possible = 0;
  26.     isPossible(A, sum, possible);
  27.     return possible;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement