LeetCode : 979. Distribute Coins in Binary Tree分布在树中的金币

喜欢ヅ旅行 2021-06-24 16:12 366阅读 0赞

试题
Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.

In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)

Return the number of moves required to make every node have exactly one coin.

Example 1:

Input: [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:

Input: [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Example 3:

Input: [1,0,2]
Output: 2
Example 4:

Input: [1,0,0,null,3]
Output: 4

Note:

1<= N <= 100
0 <= node.val <= N
代码:
首先知道树中节点没有指向父指针,显然我们要在递归返回子树需要的金币数量。
如果在当前节点能满足就尽量满足,不管是多的金币还是少的金币都需要向上统计步数。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. int total = 0;
  12. public int distributeCoins(TreeNode root) {
  13. find(root);
  14. return total;
  15. }
  16. public int find(TreeNode root){
  17. if(root==null) return 0;
  18. int l = find(root.left);
  19. int r = find(root.right);
  20. int v = root.val + l + r - 1;
  21. total += Math.abs(v);
  22. return v;
  23. }
  24. }

发表评论

表情:
评论列表 (有 0 条评论,366人围观)

还没有评论,来说两句吧...

相关阅读