Tuesday, September 3, 2019

979. Distribute Coins in Binary Tree

979. Distribute Coins in Binary Tree

https://leetcode.com/problems/distribute-coins-in-binary-tree/

  • 이문제는 풀이는 조금더 생각을 해서 코딩 라인수를 줄여야할필요가 있음

  • 실제 코인의 이동이 아니라 코인이 없더라도 음수대로 값을 채움 ( 있는것처럼 가상의 코인을 움직인다 )

  • data를 채우는것은 inorder 순서로 적용

Runtime: 1 ms, faster than 87.01% of Java online submissions for Distribute Coins in Binary Tree.
Memory Usage: 37.7 MB, less than 100.00% of Java online submissions for Distribute Coins in Binary Tree.
public class Solution {

    int count =0;
    public int distributeCoins(TreeNode root) {
        if(root == null){
            return 0;
        }
        conqer(root);

        return count;
    }

    public void conqer ( TreeNode root){
        if(root.left != null){
            conqer(root.left);
            calclator(root, root.left);
        }
        if(root.right != null){
            conqer(root.right);
            calclator(root, root.right);
        }
    }
    public void calclator(TreeNode root, TreeNode child){
        if(child.val <=0){
            int increase = 1-child.val;
            count += increase;
            child.val = 1;
            root.val = root.val - increase;
        }else {
            int decrease =  child.val - 1;
            count += decrease;
            child.val = 1;
            root.val = root.val + decrease;
        }
    }
}

No comments:

Post a Comment