In the following, we consider binary trees where only the leaves have weights. Let $T$ be a binary tree and $W(T)$ be the sum of the weights of its leaves. Let $T.l$ and $T.r$ be the left child and right child respectively.
We define the imbalance $I(T)$ of a binary tree $T$ as follows:
$$I(T) = \begin{cases} 0 & size(T) = 1\\ |W(T.l) - W(T.r)| + I(T.l) + I(T.r) & size(T)>0 \end{cases}$$
Examples
a.) * b.) *
/ \ / \
* 5 * *
/ \ / \ / \
* 3 1 5 3 3
/ \
1 3
Tree a. has imbalance 5 (2 + 1 + 2) and tree b. has imbalance 4 (4 + 0 + 0).
Consider the following problem:
Input: a list of $n$ positive integers $W = (a_1, \ldots, a_n)$, and an integer $k$.
Query: is there a binary tree $T$ with leaf weights $W$ such that $I(T) \leq k$?
Is this problem $\mathsf{NP}$-hard?
The case $k = 0$ is easy. There is a simple algorithm which goes as follows ($Q$ is a priority queue):
- for $w \in W$: $Q.push(w)$
- while $Q.size > 1$:
2.1. pop the two smallest elements $w_1$ and $w_2$ form $Q$.
2.2. if $w_1 = w_2$ then $Q.push(2*w_1)$
2.3. else return "No"- return "Yes"