979. Distribute Coins in Binary Tree
T: O(n)
S: O(n) // ่ฎฉๅฝๅ่ฟๆฃตๆ ๅนณ่กกๆ้็็งปๅจๆฌกๆฐ
Math.abs(left) + Math.abs(right) + (root.val - 1);/**
* 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 {
public int distributeCoins(TreeNode root) {
int[] result = new int[1];
dfs(root, result);
return result[0];
}
private int dfs(TreeNode node, int[] result) {
if (node == null) {
return 0;
}
int left = dfs(node.left, result);
int right = dfs(node.right, result);
// System.out.println(left);
// System.out.println(right);
// System.out.println(Math.abs(left) + Math.abs(right) + node.val - 1);
result[0] += Math.abs(left) + Math.abs(right) + node.val - 1; // move times, so need abs
return left + right + node.val - 1;
}
}
/***
ex:
3
0.
0
left = 0
right = 0
result += (Math.abs(left) + Math.abs(right) + node.val - 1) = 0 + 0 + (0-1) = -1
return -1
-> result[0] = -1;
left = -1
right = 0
result += (Math.abs(left) + Math.abs(right) + node.val - 1) = 1 + 0 + (0-1) = 0
return -2
-> result[0] = -1;
left = 2
right = 0
result += (Math.abs(left) + Math.abs(right) + node.val - 1) = 2 + 0 + (3-1) = 4
return
-> result[0] = -1 + 4 = 3;
so 3 moves
T: O(n)
S: O(n)
*/Another easy thought:
Latest
Last updated