Leetcode979: Distribute Coins in Binary Tree Binary Tree uniform distribution of the coin issue

problem

Given to the root node of a binary tree, a binary tree each node has a node.val Coins, a kind of N coins. Now requires that the mobile node in a binary tree coins coins final value of each node is 1. Every move, we can only move to adjacent contacts, that coins can only move to the parent or child node, then ask how much the final step needed to move.

Leetcode original title link: https://leetcode.com/problems/distribute-coins-in-binary-tree/

analysis

If the leaf node has 0 coins, then we need to move a coin from the parent node to a leaf node (push (-1) a coin from left node); ---- move again

If the leaf node has four nodes then we will need to push three coins to the parent node (push +3 coins from leaf node). ---- move three times

Define a dfs (node) function that represents the current node from the need to push the number of coins its parent node (in other words, the current total number of coins subtree root node in the total number of nodes by subtracting the current number) then dfs (node) = dfs (node.left) + dfs (node.right) - 1 (1 is subtracted because of a coin in a left current node), the number of steps needed to move the current node is a root node It is equal to abs (dfs (node.left)) + abs (dfs (node.right)).

achieve

  private int ans = 0;
  public int distributeCoins(TreeNode root) {
        ans = 0;
        distributeCoinsHelper(root);
        return ans;
    }
    private int dfs(TreeNode cur){
        if(cur == null){
            return 0;
        }
        int left = dfs(cur.left);
        int right = dfs(cur.right);
        ans += Math.abs(left) + Math.abs(right);
        return left + right + cur.val - 1;
    }

Guess you like

Origin www.cnblogs.com/jun-ma/p/11875985.html