KatInterview

Cheapest Edit Count to Turn a Tree into a Perfect Tree

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbinary-treebfslevel-order

Last 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, where n = len(left) = len(right)
  • Every left[i] and right[i] is either -1 or an index in [1, n - 1].
  • Every node other than 0 is the child of exactly one node, and node 0 is nobody's child, so the arrays describe one valid tree on n nodes.
  • The height of the tree can be as large as n - 1. A perfect tree of that height would have far more than 2^63 - 1 nodes, so be careful with huge intermediate values. The returned answer is always less than n.

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.