Skip to content

Commit

Permalink
Time: 7 ms (20.62%), Space: 15.5 MB (89.89%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Soumya-Kushwaha committed May 18, 2024
1 parent b05240b commit a66feb1
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:

int traverse(TreeNode* r, int &moves) {

if (r == NULL)
return 0;

int left = traverse(r->left, moves);
int right = traverse(r->right, moves);
moves += abs(left) + abs(right);
return r->val + left + right - 1;
}

int distributeCoins(TreeNode* r, int moves = 0) {
traverse(r, moves);
return moves;
}
};

0 comments on commit a66feb1

Please sign in to comment.