diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 5d1843f7..7e76feed 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -112,6 +112,7 @@ | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst) | [C](./src/938.c) | Easy | | 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree) | [C](./src/965.c) | Easy | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array) | [C](./src/977.c) | Easy | +| 979 | [Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree) | [C](./src/979.c) | Medium | | 985 | [Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries) | [C](./src/985.c) | Medium | | 997 | [Find the Town Judge](https://leetcode.com/problems/find-the-town-judge) | [C](./src/997.c) | Easy | | 1008 | [Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal) | [C](./src/1008.c) | Medium | diff --git a/leetcode/src/979.c b/leetcode/src/979.c new file mode 100644 index 00000000..b6ad8b1b --- /dev/null +++ b/leetcode/src/979.c @@ -0,0 +1,47 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct NodeDistributeInfo { + int distributeMoves; + int distributeExcess; +}; + +struct NodeDistributeInfo* getDisturb(struct TreeNode* node) { + struct NodeDistributeInfo* result = malloc(sizeof(struct NodeDistributeInfo)); + + if (node == NULL) { + result->distributeMoves = 0; + result->distributeExcess = 1; + return result; + } + + struct NodeDistributeInfo* leftDistribute = getDisturb(node->left); + struct NodeDistributeInfo* rightDistribute = getDisturb(node->right); + + int coinsToLeft = 1 - leftDistribute->distributeExcess; + int coinsToRight = 1 - rightDistribute->distributeExcess; + + // Calculate moves as excess and depth between left and right subtrees. + result->distributeMoves = leftDistribute->distributeMoves + rightDistribute->distributeMoves + abs(coinsToLeft) + abs(coinsToRight); + result->distributeExcess = node->val - coinsToLeft - coinsToRight; + + free(leftDistribute); + free(rightDistribute); + + return result; +} + +// Depth-first search . +// On each node-step we try to recombinate coins between left and right subtree. +// We know that coins are the same number that nodes, and we can get coins by depth +// Runtime: O(n) +// Space: O(1) +int distributeCoins(struct TreeNode* root) { + return getDisturb(root)->distributeMoves; +}