Make All Root to Path Sum Equal

题目:
一棵树,所有节点的value都是正整数,问只能增加某些节点值的情况下,如何调整使得从root到所有leaf的path上经过的节点值之和相等,返回增加的值的和,使这个和最小

解题思路:
这道题首先要找到max,然后更新leaf节点。

代码:

public class MakeAllRoottoPathSumEqual {

    public static void main(String[] args){
        TreeNode node4 = new TreeNode(4);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);

        node3.right = node2;
        node3.left = node1;
        node5.right = node6;
        node4.left = node3;
        node4.right = node5;

        MakeAllRoottoPathSumEqual makeAllRoottoPathSumEqual = new MakeAllRoottoPathSumEqual();
        makeAllRoottoPathSumEqual.makeEqual(node4);
        node4.print(node4);
    }

    int max = 0;
    public void makeEqual(TreeNode root){
        if(root == null){
            return;
        }
        updateMax(root, 0);
        addToLeaf(root, 0);
    }

    private void addToLeaf(TreeNode root, int prev) {
        if(root == null){
            return;
        }
        int curr = prev + root.val;
        if(root.left == null && root.right == null){
            if(curr < max){
                root.val += max - curr;
            }
            return;
        }
        addToLeaf(root.left, curr);
        addToLeaf(root.right, curr);
    }

    private void updateMax(TreeNode root, int prev) {
        if(root == null){
            return;
        }
        int curr = prev + root.val;
        if(root.left == null && root.right == null){
            max = Math.max(max, curr);
            return;
        }
        updateMax(root.left, curr);
        updateMax(root.right, curr);
    }

}




Comments

Popular Posts