LC.P979[在二叉树中分配硬币]

方法一:DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

int ans;

public int distributeCoins(TreeNode root) {
dfs(root);
return ans;
}

private int[] dfs(TreeNode node) {
if (node == null) return new int[]{0, 0};
int[] left = dfs(node.left);
int[] right = dfs(node.right);
// 子树硬币个数
int coins = left[0] + right[0] + node.val;
// 子树节点数
int nodes = left[1] + right[1] + 1;
ans += Math.abs(coins - nodes);
return new int[]{coins, nodes};
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:DFS(优化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {

int ans;

public int distributeCoins(TreeNode root) {
dfs(root);
return ans;
}

private int dfs(TreeNode node) {
if (node == null) return 0;
int d = dfs(node.left) + dfs(node.right) + node.val - 1;
ans += Math.abs(d);
return d;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$