Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
distribute-coins-in-binary-tree.cpp 668 Bytes
Copy Edit Raw Blame History
kamyu authored 2019-01-20 17:00 +08:00 . Create distribute-coins-in-binary-tree.cpp
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int distributeCoins(TreeNode* root) {
int result = 0;
dfs(root, &result);
return result;
}
private:
int dfs(TreeNode* root, int *result) {
if (!root) {
return 0;
}
int left = dfs(root->left, result);
int right = dfs(root->right, result);
*result += abs(left) + abs(right);
return root->val + left + right - 1;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

Search