Advertisement
nikunjsoni

979

Apr 23rd, 2021
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     int ans=0;
  15.     int dfs(TreeNode* curr){
  16.         if(!curr) return 0;
  17.         int L = dfs(curr->left);
  18.         int R = dfs(curr->right);
  19.         ans += abs(L)+abs(R);
  20.         return L+R+curr->val-1;
  21.     }
  22.    
  23.     int distributeCoins(TreeNode* root) {
  24.         dfs(root);
  25.         return ans;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement