Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- int moves = 0;
- public int distributeCoins(TreeNode root) {
- distribute(root);
- return moves;
- }
- private int distribute(TreeNode node) {
- if(node == null) {
- return 0;
- }
- int coinsLeft = distribute(node.left); // 1
- int coinsRight = distribute(node.right); // 1
- int coinsNode = node.val; // 1
- int coinsTotal = coinsLeft + coinsRight + coinsNode;
- moves += Math.abs(coinsLeft) + Math.abs(coinsRight);
- return coinsTotal - 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement