Skip to content

Commit 53567c9

Browse files
Added solution for distribute coins in binary tree
1 parent bc24235 commit 53567c9

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

distribute_coins_binary_tree.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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 helper(TreeNode* root, int &sum) {
15+
if(!root) return 0;
16+
17+
int l = helper(root->left, sum);
18+
int r = helper(root->right, sum);
19+
sum += abs(l) + abs(r);
20+
return root->val + l + r - 1;
21+
}
22+
23+
int distributeCoins(TreeNode* root) {
24+
int sum = 0;
25+
helper(root, sum);
26+
return sum;
27+
}
28+
};

0 commit comments

Comments
 (0)