Cheapest Edit Count to Turn a Tree into a Perfect Tree
Trees & GraphsAuto-graded · 21 test casesLast updated
Find the minimum number of leaf deletions and node insertions that make a binary tree perfect, using per-level counts and a bounded search over the target height.
A binary tree is called perfect if every node has either no children or exactly two children, and all leaves lie at the same depth. A tree with a single node is perfect.
You are given a binary tree and may edit it. Your task is to compute the smallest number of edits that turns it into a perfect tree. The answer is 0 exactly when the tree is already perfect.
The tree has n nodes labeled 0 to n - 1, and node 0 is the root. For each node i, left[i] and right[i] hold the labels of its left and right children, or -1 if that child does not exist.
Edits
Each edit costs 1. There are two kinds:
- Insert: attach a brand-new node at a currently empty left or right child slot of an existing node.
- Delete: remove a node that currently has no children.
Additional rules:
- Edits never relocate a node. Every node that survives keeps its position relative to the root.
- The final tree must be non-empty and perfect.
- Only the shape matters. Nodes carry no values.
Task
Implement min_edits_to_perfect(left, right), which returns the minimum number of edits (inserts plus deletes) needed to reach a perfect tree.
Constraints
1 <= n <= 10^5, wheren = len(left) = len(right)- Every
left[i]andright[i]is either-1or an index in[1, n - 1]. - Every node other than
0is the child of exactly one node, and node0is nobody's child, so the arrays describe one valid tree onnnodes. - The height of the tree can be as large as
n - 1. A perfect tree of that height would have far more than2^63 - 1nodes, so be careful with huge intermediate values. The returned answer is always less thann.
Examples
Example 1
Input: min_edits_to_perfect([1, 3, 5, -1, -1, -1, -1], [2, 4, 6, -1, -1, -1, -1])
Output: 0
Example 2
Input: min_edits_to_perfect([1, 3, 5, -1, -1, -1], [2, 4, -1, -1, -1, -1])
Output: 1
Example 3
Input: min_edits_to_perfect([1, 2, -1], [-1, -1, -1])
Output: 2
Hints
Hint 1
Imagine you have already decided the height h of the final perfect tree. Which of the existing nodes must be kept, and which must go?
Hint 2
For a fixed h, every existing node deeper than h must be deleted and every empty position at depth at most h must be filled. If c is the number of existing nodes at depth at most h, the cost is (n - c) + ((2^(h+1) - 1) - c). Per-level counts from a BFS give c.
Hint 3
You do not need to try every height. The cost is at least (2^(h+1) - 1) - n, and n - 1 (keep only the root) is always achievable, so stop once that lower bound reaches the best cost found. This also keeps the numbers small.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Decide the height h of the final perfect tree first. Once h is fixed, the set of nodes that remain is forced.
A perfect tree of height h occupies every position at depths 0..h and nothing deeper. Since nodes never move:
- every existing node deeper than
hmust be deleted; - every position at depth
<= hthat is currently empty must be filled by an insertion.
Let c_h be the number of existing nodes at depth <= h, and let full_h = 2^(h+1) - 1 be the size of a perfect tree of height h. Then
cost(h) = (n - c_h) + (full_h - c_h) = n + full_h - 2 * c_h
The answer is the minimum of cost(h) over all h >= 0. A single BFS yields the number of nodes at each depth, and a running prefix sum gives c_h.
Why it is correct
- Each plan for height
his legal. Delete the too-deep nodes from the deepest level upward, so each one is a leaf when removed. Then insert the missing positions from the top down, so each new node's parent already exists. - No plan for height
his cheaper. Then - c_hdeletions andfull_h - c_hinsertions are all forced. Any extra operation (such as deleting and re-inserting a node) only adds cost. - Every final tree has some height. Minimizing over all
htherefore covers every possible outcome.
Bounding the search
h = 0(keep only the root) always works and costsn - 1, sobeststarts there.- Because
c_h <= n, we havecost(h) >= full_h - n. Sincefull_hgrows withh, oncefull_h - n >= bestno larger height can improve the answer, and we stop. This happens after roughlylog2(n) + 2heights, so we never handle astronomically large numbers even for a chain of10^5nodes. - Heights beyond the input's height keep
c_h = nwhilefull_hkeeps growing, so they only get worse. Looping over the levels that exist is enough.
The traversal is iterative, so a degenerate chain of height 10^5 causes no recursion problems.
Complexity
- Time: O(n). The BFS touches each node once, and the height loop is at most O(log n) iterations.
- Space: O(n) for the BFS frontier and level widths.
Reference solution
from typing import List
def min_edits_to_perfect(left: List[int], right: List[int]) -> int:
n = len(left)
# Level-order traversal: widths[d] = number of nodes at depth d.
widths = []
level = [0]
while level:
widths.append(len(level))
nxt = []
for v in level:
if left[v] != -1:
nxt.append(left[v])
if right[v] != -1:
nxt.append(right[v])
level = nxt
# Keeping only the root always works and costs n - 1 deletions.
best = n - 1
kept = 0
for h in range(len(widths)):
full = (1 << (h + 1)) - 1
# cost(h) >= full - n, and full only grows with h.
if full - n >= best:
break
kept += widths[h]
cost = (n - kept) + (full - kept)
if cost < best:
best = cost
return best