Minimum Cost Tree From Leaf Values - Problem
Given an array arr of positive integers, consider all binary trees such that:
- Each node has either 0 or 2 children
- The values of
arrcorrespond to the values of each leaf in an in-order traversal of the tree - The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree
Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
A node is a leaf if and only if it has zero children.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [6,2,4]
›
Output:
32
💡 Note:
There are two possible trees. The first has non-leaf node sum 36, the second has non-leaf node sum 32. Tree 1: ((6,2),4) → cost = 6*2 + max(6,2)*4 = 12 + 24 = 36. Tree 2: (6,(2,4)) → cost = 2*4 + 6*max(2,4) = 8 + 24 = 32.
Example 2 — Minimum Size
$
Input:
arr = [4,11]
›
Output:
44
💡 Note:
Only one possible tree with root having value 4*11 = 44.
Example 3 — Multiple Elements
$
Input:
arr = [1,2,3,4]
›
Output:
28
💡 Note:
Optimal grouping: (1,(2,(3,4))) → costs: 3*4=12, 2*4=8, 1*4=4, total=28.
Constraints
- 2 ≤ arr.length ≤ 40
- 1 ≤ arr[i] ≤ 15
- It is guaranteed that the answer fits in a 32-bit signed integer (i.e., it is less than 231)
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [6,2,4] representing leaf values in in-order traversal
2
Process
Build binary trees where internal nodes = product of max values from left and right subtrees
3
Output
Return minimum sum of all internal node values
Key Takeaway
🎯 Key Insight: Always remove smaller elements first using a monotonic stack to minimize total cost
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code