Advertisement
K_S_

Untitled

Nov 21st, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.77 KB | None | 0 0
  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.    
  12.     int moves = 0;
  13.  
  14.     public int distributeCoins(TreeNode root) {
  15.         distribute(root);
  16.         return moves;
  17.     }
  18.  
  19.     private int distribute(TreeNode node) {
  20.         if(node == null) {
  21.             return 0;
  22.         }
  23.  
  24.         int coinsLeft = distribute(node.left);      // 1
  25.         int coinsRight = distribute(node.right);    // 1
  26.         int coinsNode = node.val;                   // 1
  27.         int coinsTotal = coinsLeft + coinsRight + coinsNode;
  28.  
  29.         moves += Math.abs(coinsLeft) + Math.abs(coinsRight);
  30.  
  31.         return coinsTotal - 1;
  32.     }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement