Skip to main content

Make Costs of Paths Equal in a Binary Tree - Solution & Explanation

MediumArrayDynamic ProgrammingGreedyTree21 min readAsked at: Tiktok
Practice this problem

Problem Statement

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.

Each node in the tree also has a cost represented by a given 0-indexed integer array cost of size n where cost[i] is the cost of node i + 1. You are allowed to increment the cost of any node by 1 any number of times.

Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.

Note:

  • A perfect binary tree is a tree where each node, except the leaf nodes, has exactly 2 children.
  • The cost of a path is the sum of costs of nodes in the path.

 

Example 1:

Input: n = 7, cost = [1,5,2,2,3,3,1]
Output: 6
Explanation: We can do the following increments:
- Increase the cost of node 4 one time.
- Increase the cost of node 3 three times.
- Increase the cost of node 7 two times.
Each path from the root to a leaf will have a total cost of 9.
The total increments we did is 1 + 3 + 2 = 6.
It can be shown that this is the minimum answer we can achieve.

Example 2:

Input: n = 3, cost = [5,3,3]
Output: 0
Explanation: The two paths already have equal total costs, so no increments are needed.

 

Constraints:

  • 3 <= n <= 105
  • n + 1 is a power of 2
  • cost.length == n
  • 1 <= cost[i] <= 104

Approach Overview

Problem Overview: You are given a complete binary tree represented by an array cost. Each node has a cost, and the goal is to make every root‑to‑leaf path have the same total cost. You can increment node values any number of times. The task is to compute the minimum number of increments required so all path sums become equal.

Approach 1: Recursive Bottom-Up DFS (Greedy) (Time: O(n), Space: O(h))

This approach processes the tree from the leaves upward using recursion. For each node, compute the total path cost coming from its left and right children. If the two subtree costs differ, you add the difference to the answer because you must increment the smaller side to match the larger one. Return the current node cost plus the larger subtree sum to the parent. The greedy insight: equalize paths locally at every node so the larger path propagates upward. This method naturally fits a postorder traversal of a tree or binary tree, ensuring each subtree is balanced before combining them.

Approach 2: Iterative Bottom-Up with Queue (Time: O(n), Space: O(n))

The iterative approach simulates the same bottom‑up idea without recursion. Because the tree is stored in an array, children of node i are 2*i and 2*i+1 (1-indexed). Start from the last internal node and move upward. For each node, compare the accumulated path costs of its two children, add the absolute difference to the answer, then update the parent cost by adding the larger child path. A queue or simple reverse traversal ensures children are processed before parents.

Recommended for interviews: The recursive greedy DFS is the solution most interviewers expect. It demonstrates strong understanding of postorder traversal and local balancing of subtree costs. The iterative array-based version proves you understand how complete binary trees map to arrays and how to simulate bottom‑up dynamic programming without recursion.

Approach 1: Recursive Approach

This approach involves recursively calculating the cost of each path from the root to the leaf and ensuring all paths have the same cost by incrementing node costs where necessary.

We create an array to store the cumulative path costs from each node to the leaves. Starting from the last node, we calculate the path cost by checking the costs from its child nodes. This ensures we have path costs for all root to leaf paths. The maximum path cost is then used to calculate the number of increments needed to make all paths equal.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) as each node is processed once.
Space Complexity: O(n) to store path costs.

Try this approach in the editor →

Approach 2: Iterative Approach with Queue

This approach uses an iterative level-order traversal of the binary tree, utilizing a queue to manage nodes, while keeping track of path costs level-by-level.

This implementation iteratively calculates the maximum path costs using a straightforward loop. We gather costs up the tree while modifying increment counts through a greedy approach, which ensures each node's child paths are maximized efficiently.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) as each node is checked once.
Space Complexity: O(n) for path cost storage.

Try this approach in the editor →

Approach 3: Greedy Algorithm

According to the problem description, we need to calculate the minimum number of increments to make the path values from the root node to each leaf node equal.

The path values from the root node to each leaf node being equal is actually equivalent to the path values from any node as the root of a subtree to each leaf node of that subtree being equal.

Why is that? We can prove it by contradiction. Suppose there is a node x, and the path values from it as the root of a subtree to some leaf nodes are not equal. Then there exists a situation where the path values from the root node to the leaf nodes are not equal, which contradicts the condition "the path values from the root node to each leaf node are equal". Therefore, the assumption is not valid, and the path values from any node as the root of a subtree to each leaf node of that subtree are equal.

We can start from the bottom of the tree and calculate the number of increments layer by layer. For each non-leaf node, we can calculate the path values of its left and right child nodes. The number of increments is the difference between the two path values, and then update the path values of the left and right child nodes to the larger one of the two.

Finally, return the total number of increments.

The time complexity is O(n), where n is the number of nodes. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Recursive Approach

Time Complexity: O(n) as each node is processed once.
Space Complexity: O(n) to store path costs.

Iterative Approach with Queue

Time Complexity: O(n) as each node is checked once.
Space Complexity: O(n) for path cost storage.

Greedy Algorithm

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Bottom-Up DFS (Greedy)O(n)O(h)Best general solution. Clean postorder traversal with minimal extra memory.
Iterative Bottom-Up with QueueO(n)O(n)Useful when recursion depth is limited or when working directly with array-based trees.

Video Solution

Leetcode weekly contest 344 | 2673. Make Costs of Paths Equal in a Binary Tree | HindiPawan Kumar Giri1,113 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Make Costs of Paths Equal in a Binary Tree easy or hard?
The problem is rated Medium difficulty on LeetCode with an acceptance rate around 58%. The main challenge is recognizing the greedy bottom‑up pattern. Once you identify that subtree path sums must be equalized locally, the implementation becomes straightforward.
Make Costs of Paths Equal in a Binary Tree Python/Java solution
In Python or Java, implement a recursive DFS that returns the maximum subtree path sum. At each node, compute left and right sums, add their absolute difference to a global counter, and return the node value plus the larger child sum. Both implementations run in O(n) time and require only recursion stack space.
How to solve Make Costs of Paths Equal in a Binary Tree in O(n)?
Process the tree bottom‑up using postorder traversal. For every node, compute the path sums of its left and right subtrees. Add the absolute difference between those sums to the total operations and return the node value plus the larger subtree sum. Since each node is visited once, the total runtime remains O(n).
What is the best approach for Make Costs of Paths Equal in a Binary Tree?
The optimal solution uses a greedy bottom‑up DFS. Traverse the tree in postorder, compute the path sums from the left and right children, and add the difference between them to the result. Propagate the larger subtree cost upward. This ensures all root‑to‑leaf paths become equal with the minimum number of increments in O(n) time.
Is Make Costs of Paths Equal in a Binary Tree asked at Google/Amazon/Meta?
Binary tree balancing and path sum equalization problems appear in interviews at companies like Google, Amazon, and Meta. Variations often test postorder traversal, greedy balancing, and tree dynamic programming. This problem is a good practice example for those patterns.
What data structure is used in Make Costs of Paths Equal in a Binary Tree?
The core data structure is a complete binary tree stored as an array. The algorithm performs a postorder traversal using recursion or a bottom‑up iteration. Greedy comparisons between left and right subtree sums ensure balanced path costs.
What is the time complexity of Make Costs of Paths Equal in a Binary Tree?
The optimal algorithm runs in O(n) time because every node in the binary tree is processed exactly once. Each step performs constant work: comparing child path sums and updating the result. Space complexity is O(h) for recursion stack depth, where h is the tree height.

Ready to solve this problem?

Practice Make Costs of Paths Equal in a Binary Tree with our built-in code editor and test cases.

Practice on FleetCode