Make Costs of Paths Equal in a Binary Tree — LeetCode 2673 Python Solution

MediumGreedyTreeArrayDynamic ProgrammingBinary Tree
Problem
#2673
Reading time
2 min

The problem

You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n. The root of the tree is node 1 and each node i in the tree has two children where the left child is the node 2 * i and the right child is 2 * i + 1.

Example

Input
n = 7, cost = [1,5,2,2,3,3,1]
Output
6
Explanation
We can do the following increments:

Python solution

Python
class Solution:
    def minIncrements(self, n: int, cost: List[int]) -> int:
        ans = 0
        for i in range(n >> 1, 0, -1):
            l, r = i << 1, i << 1 | 1
            ans += abs(cost[l - 1] - cost[r - 1])
            cost[i - 1] += max(cost[l - 1], cost[r - 1])
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the number of nodes
SpaceO(1) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2673. Make Costs of Paths Equal in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2673. Make Costs of Paths Equal in a Binary Tree?
LeetCode 2673. Make Costs of Paths Equal in a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 2673. Make Costs of Paths Equal in a Binary Tree?
The Python solution on this page runs in O(n), where n is the number of nodes.
What is the space complexity of LeetCode 2673. Make Costs of Paths Equal in a Binary Tree?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2673. Make Costs of Paths Equal in a Binary Tree cover?
LeetCode 2673. Make Costs of Paths Equal in a Binary Tree is tagged Greedy, Tree, Array, Dynamic Programming and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview